本文主要是介绍59. Spiral Matrix II(待进一步研究),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 ]
]
四步走:
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++;} elseif (dir == 1) {i++;if (i == n || matrix[i][j] != 0) dir = 2, i--, j--;} elseif (dir == 2) {j--;if (j < 0 || matrix[i][j] != 0) dir = 3, j++, i--;} elseif (dir == 3) {i--;if (i < 0 || matrix[i][j] != 0) dir = 0, i++, j++;}}return matrix;}
这篇关于59. Spiral Matrix II(待进一步研究)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!