59. spiral matrix

description

给出两道题,同类型的:
一道是返回顺时针矩阵的列表
一道是生成顺时针矩阵

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5]

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 ]
]

思路与题解

实质上是自走迷宫,大问题化为小问题,每次都是右下左上,当不能走时表示结束

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
54
55
56
57
58
59
60
61
62
public List<Integer> (int[][] matrix) {
List<Integer> arr=new ArrayList<>();
if(matrix==null||matrix.length==0)return arr;
int len1s,len2s,len1e,len2e;
len1s=len2s=0;
len1e=matrix.length-1;
len2e=matrix[0].length-1;
int i,j;
i=j=0;
while (true){
switch (1){
case 1:
if(j<=len2e){
while (j<=len2e){
arr.add(matrix[i][j]);
j++;
}
j--;
i++;
len1s++;
}else {
return arr;
}
case 2:
if(i<=len1e){
while (i<=len1e){
arr.add(matrix[i][j]);
i++;
}
i--;
j--;
len2e--;
}else {
return arr;
}
case 3:
if(j>=len2s){
while (j>=len2s){
arr.add(matrix[i][j]);
j--;
}
j++;
i--;
len1e--;
}else {
return arr;
}
case 4:
if(i>=len1s){
while (i>=len1s){
arr.add(matrix[i][j]);
i--;
}
i++;
j++;
len2s++;
}else {
return arr;
}
}
}
}
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
public int[][] generateMatrix(int n) {
int[][] arr=new int[n][n];
if(n==0)return arr;
int num=0;
int i,j;
int left,right,on,under;
i=j=0;
left=on=0;
right=under=n-1;
while (true) {
if (i <=right) {
while (i <= right) {
arr[j][i] = ++num;
i++;
}
i--;
j++;
on++;
}else return arr;
if (j <= under) {
while (j<=under){
arr[j][i]=++num;
j++;
}
j--;
i--;
right--;
}else return arr;
if(i>=left){
while (i>=left){
arr[j][i]=++num;
i--;
}
i++;
j--;
under--;
}else return arr;
if(j>=on){
while (j>=on){
arr[j][i]=++num;
j--;
}
j++;
i++;
left++;
}else return arr;
}
}