Given an integer n, generate a square matrix filled with elements from 1 ton2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路:这个算法跟之前的 Sprial Matrix I,一模一样。
class Solution {
public int[][] generateMatrix(int n) {
int startX = 0; int endX = n - 1;
int startY = 0; int endY = n - 1;
int[][] res = new int[n][n];
int value = 1;
while(startX <= endX && startY <= endY) {
// top;
for(int j = startY; j <= endY; j++) {
res[startX][j] = value++;
}
if(++startX > endX) break;
// right;
for(int i = startX; i <= endX; i++) {
res[i][endY] = value++;
}
if(--endY < startY) break;
// bottom;
for(int j = endY; j >= startY; j--) {
res[endX][j] = value++;
}
if(--endX < startX) break;
// left;
for(int i = endX; i >= startX; i--) {
res[i][startY] = value++;
}
if(++startY > endY) break;
}
return res;
}
}