首页 > 代码库 > [LeetCode] Spiral Matrix II
[LeetCode] 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 ]]
class Solution {public: vector<vector<int> > generateMatrix(int n) { vector<int> v(n,0); vector<vector<int>> res(n,v); int col = (n+1)/2-1;//结束点的行列号 int row = n/2; int num = 1; int rowStart=0,rowEnd=n-1,colStart=0,colEnd=n-1; int j=colStart,i=rowStart ; while(1) { for(j = colStart;j<=colEnd;j++) { res[i][j] = num++; } j = j-1; if(i==row && j==col) break; rowStart++; j = colEnd; for(i=rowStart;i<=rowEnd;i++) { res[i][j] = num++; } colEnd--; i = rowEnd; for(j=colEnd;j>=colStart;j--) { res[i][j] = num++; } j = j+1; if(i==row && j==col) break; rowEnd--; j=colStart; for(i = rowEnd;i>=rowStart;i--) { res[i][j] = num++; } colStart++; i = rowStart; }//end while return res; }};
[LeetCode] Spiral Matrix II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。