classSolution {public: vector<vector<int> > generateMatrix(intn) { vector<int>sub(n); vector<vector<int> >ans(n, sub);// 也可以用vector<vector<int> > ans(n, vector<int>(n));if(n <1)returnans;intval =1, left =0, right = n-1, up =1, down = n-1;for(inti =0; i < ...
还是与上一题Spiral Matrix类似的算法,使用Direction 数组来定义旋转方向。其实蛮复杂的,也不好记。但是记住了应该是标准的算法。 View Code SOLUTION 3: 无比巧妙的办法,某人的男朋友可真是牛逼啊![leetcode] Spiral Matrix | 把一个2D matrix用螺旋方式打印 此方法的巧妙之处是使用TOP,BOOTOM, LEFT, RIGHT ...
【leetcode】Spiral Matrix II Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. For example,Given n = 3, You should return the following matrix:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]] 1 class Solution { 2 public: 3 ...
关键点:螺旋矩阵的遍历模式;设置四个边界值 1publicclassSolution2{3publicint[][] generateMatrix(intn)4{5int[][] res =newint[n][n];67inttotal = n*n;8intnum = 1;910introwBegin = 0;11introwEnd = n-1;12intcolBegin = 0;13intcolEnd = n-1;1415while(num <=total)16{17//traverse ...
> > generateMatrix(int n) { 4 // Note: The Solution object is instantiated only once and is reused by each test case.5 vector<vector<int> > matrix; 6 if (n<=0) 7 return matrix; 8 int flag[4] = {0, n-1, 0, n-...
与Spriral Matrix(http://fisherlei.blogspot.com/2013/01/leetcode-spiral-matrix.html)类似,区别在于一个用递归来剥皮,一个用递归来构造。Code可以复用。 [Code] 红色部分为改动部分。可以看出来,与Spriral Matrix的code相比,改动非常小。 1: vector<vector<int> >generateMatrix(int n) { ...
跟Spiral Matrix一样的处理,甚至还简单一些,这个确定是方阵。分层,然后按照上右下左的顺序放入数组中。每个元素只访问一次,时间复杂度是O(n^2)。 1publicclassSolution {2publicint[][] generateMatrix(intn) {3int[][] res =newint[n][n];4if(n < 0)returnnull;5intlevelNum = n / 2;6intcount ...
matrix[x][endy] = num++; } // 如果行或列遍历完,则退出循环 if (startx == endx || starty == endy) { break; } // 下边的行,从右向左 for (int y = endy - 1; y >= starty; y--) { matrix[endx][y] = num++;
1publicclassSolution {2publicint[][] generateMatrix(intn) {3int[][] matrix =newint[n][n];4intleft = 0;5intright = n-1;6intup = 0;7intdown = n-1;8intnumber = 0;9while(number <= n*n-1){10for(inti = left;i <= right;i++){11matrix[up][i] = number+1;12number++;...
You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] Solution: classSolution {public:int**used; vector<vector<int> > generateMatrix(intn) { vector< vector<int> >ans;if(n ==0)returnans; ...