59. Spiral Matrix II

59. Spiral Matrix II

Question

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Solution

用数字表示方向,根据方向决定坐标移动的方式。

当方向改变时,减少对应的边界。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public int[][] generateMatrix(int n) {
int dir = 0;
int p = 0, q = 0;
int right = n-1, down = n-1;
int left = 0, up = 0;
int count = 0;
int[][] ret = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
switch(dir){
case 0:
count++;
ret[p][q] = count;
q++;
if(q == right){
up++;
dir = 1;
}
break;
case 1:
count++;
ret[p][q] = count;
p++;
if(p == down){
right--;
dir = 2;
}
break;
case 2:
count++;
ret[p][q] = count;
q--;
if(q == left){
down--;
dir = 3;
}
break;
case 3:
count++;
ret[p][q] = count;
p--;
if(p == up){
left++;
dir = 0;
}
break;
}
}
}
return ret;
}
}
Author

Xander

Posted on

2023-05-11

Updated on

2023-05-11

Licensed under

Comments