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 ]
]
和54.Spiral Matrix类似,解法思路也无新奇,只需要维护好计数即可。
public int[][] generateMatrix(int n) {
if (n <= 0) {
return new int[0][0];
}
int[][] res = new int[n][n];
int max = n * n;
int i = 1;
int cx = 0, cy = 0;
int rowBegin = 0, rowEnd = n - 1;
int colBegin = 0, colEnd = n - 1;
while (i <= max) {
while (cy <= colEnd) {
res[cx][cy] = i;
cy++;
i++;
}
rowBegin--;
cy--;
cx++;
while (cx <= rowEnd) {
res[cx][cy] = i;
cx++;
i++;
}
colEnd--;
cx--;
cy--;
while (cy >= colBegin) {
res[cx][cy] = i;
cy--;
i++;
}
rowEnd--;
cy++;
cx--;
while (cx >= rowBegin) {
res[cx][cy] = i;
cx--;
i++;
}
colBegin--;
cx++;
cy++;
}
return res;
}
discuss中没有用cx cy记录当前点的坐标,代码清爽很多。
public static int[][] generateMatrix(int n) {
int[][] ret = new int[n][n];
int left = 0,top = 0;
int right = n -1,down = n - 1;
int count = 1;
while (left <= right) {
for (int j = left; j <= right; j ++) {
ret[top][j] = count++;
}
top ++;
for (int i = top; i <= down; i ++) {
ret[i][right] = count ++;
}
right --;
for (int j = right; j >= left; j --) {
ret[down][j] = count ++;
}
down --;
for (int i = down; i >= top; i --) {
ret[i][left] = count ++;
}
left ++;
}
return ret;
}