59. Spiral Matrix II
by Botao Xiao
Question:
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Thinking:
- Method:
- 参考54. Spiral Matrix
- 结束条件可以增加一项,通过判断当前填入数字的大小判断退出循环。
class Solution {
public int[][] generateMatrix(int n) {
if(n == 0) return null;
int[][] result = new int[n][n];
int dir = 0; //0: right, 1:down, 2:left, 3:up
int left = 0; int up = 0; int right = n - 1; int down = n - 1;
int x = 0; int y = 0;
int count = 1;
result[x][y] = count;
while(up <= down && right >= left && count <= n * n){
switch(dir){
case 0:
while(++y <= right){
result[x][y] = ++count;
}
up++;
y--;
dir = 1;
break;
case 1:
while(++x <= down){
result[x][y] = ++count;
}
right--;
x--;
dir = 2;
break;
case 2:
while(--y >= left){
result[x][y] = ++count;
}
down--;
y++;
dir = 3;
break;
case 3:
while(--x >= up){
result[x][y] = ++count;
}
left++;
x++;
dir = 0;
break;
default:
break;
}
}
return result;
}
}
二刷
class Solution {
public int[][] generateMatrix(int n) {
if(n == 0) return null;
int[][] result = new int[n][n];
int up = 0, down = n - 1, left = 0, right = n - 1;
int count = 1;
result[0][0] = 1;
int dir = 0, x = 0, y = 0;
while(up <= down && left <= right){
switch(dir){
case 0:
while(++y <= right)
result[x][y] = ++count;
y--; up++;
dir = 1;
break;
case 1:
while(++x <= down)
result[x][y] = ++count;
x--; right--;
dir = 2;
break;
case 2:
while(--y >= left)
result[x][y] = ++count;
++y; down--;
dir = 3;
break;
case 3:
while(--x >= up)
result[x][y] = ++count;
++x; left++;
dir = 0;
break;
default:
break;
}
}
return result;
}
}
Subscribe via RSS