59. Spiral Matrix II
2017-07-30 17:23
417 查看
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<int> tmp;
vector<vector<int>> res;
if(n==0)
return res;
for(int i=0;i<n;i++){
tmp.push_back(0);
}
for(int i=0;i<n;i++){
res.push_back(tmp);
}
int nr=n,nc=n;
vector<vector<int>> dir{{0,1},{1,0},{0,-1},{-1,0}};
int ndir=0;
vector<int> edge{nc,nr-1};
//int x=0,y=0,count=1; 当y初始设为0的话,报错,越界错误
int x=0,y=-1,count=1;
while(edge[ndir%2]){
for(int i=0;i<edge[ndir%2];i++){
x+=dir[ndir%4][0];
y+=dir[ndir%4][1];
res[x][y]=count;
count++;
}
edge[ndir%2]--;
ndir=(ndir+1)%4;
}
return res;
}
};
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> tmp;
vector<vector<int>> res;
if(n==0)
return res;
for(int i=0;i<n;i++){
tmp.push_back(0);
}
for(int i=0;i<n;i++){
res.push_back(tmp);
}
int nr=n,nc=n;
vector<vector<int>> dir{{0,1},{1,0},{0,-1},{-1,0}};
int ndir=0;
vector<int> edge{nc,nr-1};
//int x=0,y=0,count=1; 当y初始设为0的话,报错,越界错误
int x=0,y=-1,count=1;
while(edge[ndir%2]){
for(int i=0;i<edge[ndir%2];i++){
x+=dir[ndir%4][0];
y+=dir[ndir%4][1];
res[x][y]=count;
count++;
}
edge[ndir%2]--;
ndir=(ndir+1)%4;
}
return res;
}
};
相关文章推荐
- leetcode ----59. Spiral Matrix II
- [leetcode-59]spiral matrixII(java)
- 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- 个人记录-LeetCode 59. Spiral Matrix II
- leetcode[59]Spiral Matrix II
- [Leetcode] 59. Spiral Matrix II
- 59. Spiral Matrix II
- leetcode59 Spiral Matrix II
- LeetCode59 Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59.Spiral Matrix II
- 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode.54(59) Spiral Matrix && II
- 59. Spiral Matrix II