首页 > 代码库 > 【LeetCode】Spiral Matrix II
【LeetCode】Spiral Matrix II
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 ]]
与Spiral Matrix实现基本一致,只不过上题是遍历输出,这题是遍历输入。
class Solution {public: vector<vector<int> > generateMatrix(int n) { //n by n matrix vector<vector<int> > matrix(n, vector<int>(n,0)); if(n == 0) return matrix; int level = (n%2==0)?(n/2):(n/2+1); int number = 1; for(int i = 0; i < level; i ++) { //from up-left to up-right for(int j = i; j < n-i; j ++) matrix[i][j] = number++; //from up-right to down-right for(int j = i+1; j < n-i; j ++) matrix[j][n-1-i] = number++; //from down-right to down-left for(int j = n-1-i-1; j >= i; j --) matrix[n-1-i][j] = number++; //from down-left to up-left for(int j = n-1-i-1; j > i; j --) matrix[j][i] = number++; } return matrix; }};
【LeetCode】Spiral Matrix II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。