59. Spiral Matrix II(待进一步研究)
2017-02-23 11:15
381 查看
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
四步走:
也可以采用定义的4个变量来写,这样更清晰些(注意:此题中注释掉的两个if语句可加可不加,加上更严谨些,但注意对于n*n的矩阵可不加if,但对于m*n的矩阵则需要加上if):
更好的算法:
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
四步走:
vector<vector<int>> generateMatrix(int n) { vector<vector<int>> result(n,vector<int>(n)); int k = 1; int i = 0; while(k <= n * n){ //四个步骤 int j = i; while(j < n - i){ //水平赋值,从左到右 result[i][j++] = k++; } j = i + 1; while(j < n - i){//垂直赋值,从上到下 result[j++][n - i - 1] = k++; } j = n - i - 2; while(j > i){//水平赋值,从右到左 result[n - i - 1][j--] = k++; } j = n - i -1; while(j > i){//垂直赋值,从下到上 result[j--][i] = k++; } i++; } return result; }
也可以采用定义的4个变量来写,这样更清晰些(注意:此题中注释掉的两个if语句可加可不加,加上更严谨些,但注意对于n*n的矩阵可不加if,但对于m*n的矩阵则需要加上if):
vector<vector<int>> generateMatrix(int n) { vector<vector<int>> result(n,vector<int>(n)); int rowStart = 0; int rowEnd = n - 1; int colStart = 0; int colEnd = n -1; int k = 1; while(rowStart <= rowEnd && colStart <= colEnd){ //四步走 //第一步:水平赋值,从左到右 for(int i = colStart; i <= colEnd; i++) { result[rowStart][i] = k++; } rowStart++; //第二步,垂直赋值,从上到下 for(int i = rowStart; i <= rowEnd; i++) { result[i][colEnd] = k++; } colEnd--; //第三步,水平赋值,从右到左 for(int i = colEnd; i >= colStart; i--) { //if (rowStart <= rowEnd) result[rowEnd][i] = k++; } rowEnd--; //第四步,垂直赋值,从下到上 for(int i = rowEnd; i >= rowStart; i--) { //if (colStart <= colEnd) result[i][colStart] = k++; } colStart++; } return result; }
更好的算法:
vector<vector<int> > generateMatrix(int n) { int dir = 0; vector< vector<int> > matrix(n, vector<int> (n, 0)); int i = 0, j = 0, k = 1; while (k <= n * n) { matrix[i][j] = k++; if (dir == 0){ j++; if (j == n || matrix[i][j] != 0) dir = 1, j--, i++; } else if (dir == 1) { i++; if (i == n || matrix[i][j] != 0) dir = 2, i--, j--; } else if (dir == 2) { j--; if (j < 0 || matrix[i][j] != 0) dir = 3, j++, i--; } else if (dir == 3) { i--; if (i < 0 || matrix[i][j] != 0) dir = 0, i++, j++; } } return matrix; }
相关文章推荐
- [LeetCode] 59. Spiral Matrix II
- 59. Spiral Matrix II
- [LeetCode]59 Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- 个人记录-LeetCode 59. Spiral Matrix II
- 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- Array-----59. Spiral Matrix II(蛇形打印矩阵)
- LeetCode-59-Spiral Matrix II(C语言实现)
- leetcode@ [54/59] Spiral Matrix & Spiral Matrix II
- 59. Spiral Matrix II
- <LeetCode OJ> 54 / 59 Spiral Matrix( I / II )
- LeetCode 59 Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- LeetCode --- 59. Spiral Matrix II
- 【LeetCode】(59)Spiral Matrix II(Medium)
- 【C++】【LeetCode】54. Spiral Matrix && 59. Spiral Matrix II
- LeetCode 59 Spiral Matrix II