您的位置:首页 > 其它

59. Spiral Matrix II

2017-03-18 13:25 288 查看
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 ]
]


Subscribe to see which companies asked this question.
public class Solution {
public int[][] generateMatrix(int n) {
int[][] re = new int

;
int up = 0;
int down = n - 1;
int left = 0;
int right = n - 1;
int posi = 0;
int posj = 0;
int i = 0;
int sum = n * n;
while (i < sum) {
while (posj <= right) {
re[posi][posj] = i + 1;
posj++;
i++;
}
if (i == sum)
break;
posj--;
posi++;
up++;
while (posi <= down) {
re[posi][posj] = i + 1;
posi++;
i++;
}
if (i == sum)
break;
posi--;
posj--;
right--;
while (posj >= left) {
re[posi][posj] = i + 1;
posj--;
i++;
}
if (i == sum)
break;
posj++;
posi--;
down--;
while (posi >= up) {
re[posi][posj] = i + 1;
posi--;
i++;
}
if (i == sum)
break;
posi++;
posj++;
left++;
}
return re;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: