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 ] ]
和spiral matrix1很像,代码如下:
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545 }
public class Solution {
public int[][] generateMatrix(int n) {
int[][] res= new int
;
if(n==0) return res;
if(n==1){
res[0][0] = 1;
return res;
}
int rowbegin = 0;
int rowend = n-1;
int colbegin = 0;
int colend = n-1;
int num = 1;
while(true){
for(int i=colbegin;i<=colend;i++){
res[rowbegin][i] = num++;
}
rowbegin++;
if(rowbegin>rowend) break;
for(int i=rowbegin;i<=rowend;i++){
res[i][colend] = num++;
}
colend--;
if(colbegin>colend) break;
for(int i=colend;i>=colbegin;i--){
res[rowend][i] = num++;
}
rowend--;
if(rowbegin>rowend) break;
for(int i=rowend;i>=rowbegin;i--){
res[i][colbegin] = num++;
}
colbegin++;
if(colbegin>colend) break;
}
return res;
}
}
- leetcode59 Spiral Matrix II
- LeetCode59 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
- 59. Spiral Matrix II(待进一步研究)
- LeetCode --- 59. Spiral Matrix II
- Leetcode:59. Spiral Matrix II
- 59. Spiral Matrix II
- (Java)LeetCode-59. Spiral Matrix II
- 59. Spiral Matrix II
- 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