59. Spiral Matrix II
2017-12-20 10:16
204 查看
1、题目描述
输入数字n,返回旋转着填入n*n矩阵的矩阵。
2、思路
模拟
3、代码
vector<vector<int>> generateMatrix(int n) {
vector<vector<int> > ans(n,vector<int>(n,0));
int k=1,count = n*n;
int t=0,b=n-1,l=0,r=n-1;
while(k<=count){
for(int i = l;i<=r&&k<=count;i++){
ans[t][i]=k;
k++;
}
t++;
for(int i=t;i<=b&&k<=count;i++){
ans[i][r]=k;
k++;
}
r--;
for(int i=r;i>=l&&k<=count;i--){
ans[b][i]=k;
k++;
}
b--;
for(int i = b;i>=t&&k<=count;i--){
ans[i][l]=k;
k++;
}
l++;
}
return ans;
}
输入数字n,返回旋转着填入n*n矩阵的矩阵。
2、思路
模拟
3、代码
vector<vector<int>> generateMatrix(int n) {
vector<vector<int> > ans(n,vector<int>(n,0));
int k=1,count = n*n;
int t=0,b=n-1,l=0,r=n-1;
while(k<=count){
for(int i = l;i<=r&&k<=count;i++){
ans[t][i]=k;
k++;
}
t++;
for(int i=t;i<=b&&k<=count;i++){
ans[i][r]=k;
k++;
}
r--;
for(int i=r;i>=l&&k<=count;i--){
ans[b][i]=k;
k++;
}
b--;
for(int i = b;i>=t&&k<=count;i--){
ans[i][l]=k;
k++;
}
l++;
}
return ans;
}
相关文章推荐
- 59. Spiral Matrix II LeetCode
- 59. Spiral Matrix II
- Leetcode 59. Spiral Matrix II
- 59. Spiral Matrix II
- leetcode59-Spiral Matrix II(生成蛇形矩阵)
- [Leetcode] 59. Spiral Matrix II
- leetcode[59]Spiral Matrix II
- [LeetCode] 59. Spiral Matrix II
- 59. Spiral Matrix II
- leetcode-java-59. Spiral Matrix II
- Medium 59题 Spiral Matrix II
- 59.Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- leecode 解题总结:59. Spiral Matrix II
- 59. Spiral Matrix II
- LeetCode --- 59. Spiral Matrix II
- LeetCode.54(59) Spiral Matrix && II
- <LeetCode OJ> 54 / 59 Spiral Matrix( I / II )