您的位置:首页 > 其它

59. Spiral Matrix II

2017-02-23 04:03 218 查看
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 I,螺旋遍历,只是这里因为是n*n的矩阵,所以不用做代码中的判断:
public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int

;
if (n < 1) {
return res;
}
int rowBegin = 0, rowEnd = n - 1;
int colBegin = 0, colEnd = n - 1;
int num = 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
for (int i = colBegin; i <= colEnd; i ++) {
res[rowBegin][i] = num;
num ++;
}
rowBegin ++;
for (int i = rowBegin; i <= rowEnd; i ++) {
res[i][colEnd] = num;
num ++;
}
colEnd --;
//if (rowBegin <= rowEnd) {
for (int i = colEnd; i >= colBegin; i --) {
res[rowEnd][i] = num;
num ++;
}
rowEnd --;
//}
//if (colBegin <= colEnd) {
for (int i = rowEnd; i >= rowBegin; i --) {
res[i][colBegin] = num;
num ++;
}
colBegin ++;
//}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: