54. Spiral Matrix

54. Spiral Matrix

Question

Given an m x n matrix, return all elements of the matrix 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
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<Integer>();
int m = -1, n = 0;
int leftX = 0, leftY = 0;
int rightX = matrix[0].length - 1, rightY = matrix.length - 1;
int dir = 0;
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
switch( dir ){
case 0:
m++;
ans.add(matrix[n][m]);
if(m == rightX){
leftY++;
dir = 1;
}
break;
case 1:
n++;
ans.add(matrix[n][m]);
if(n == rightY){
rightX--;
dir = 2;
}
break;
case 2:
m--;
ans.add(matrix[n][m]);
if(m == leftX){
rightY--;
dir = 3;
}
break;
case 3:
n--;
ans.add(matrix[n][m]);
if(n == leftY){
leftX++;
dir = 0;
}
break;
}
}
}
return ans;
}
}
Author

Xander

Posted on

2023-05-11

Updated on

2023-05-11

Licensed under

Comments