0%

剑指offer-29

题目

结果

代码

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
63
64
65
66
class Solution {
private final int RIGHT = 0, DOWN = 1, LEFT = 2, UP = 3;
private int direction = 0;
private boolean[][] flag;

public int[] spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
if (matrix.length == 0) {
return new int[0];
}
flag = new boolean[matrix.length][matrix[0].length];
int i = 0, j = 0;
while (true) {
flag[i][j] = true;
ans.add(matrix[i][j]);
if (!reachable(matrix, i, j)) {
direction = (direction + 1) % 4;
if (!reachable(matrix, i, j)) {
break;
}
}
if (direction == RIGHT) {
j++;
} else if (direction == DOWN) {
i++;
} else if (direction == LEFT) {
j--;
} else if (direction == UP) {
i--;
}
}
int[] array = new int[ans.size()];
for (int k = 0; k < array.length; k++) {
array[k] = ans.get(k);
}
return array;
}

private boolean reachable(int[][] matrix, int row, int col) {
if (direction == RIGHT) {
if (col + 1 >= matrix[0].length) {
return false;
} else return !flag[row][col + 1];
}

if (direction == DOWN) {
if (row + 1 >= matrix.length) {
return false;
} else return !flag[row + 1][col];
}

if (direction == LEFT) {
if (col - 1 < 0) {
return false;
} else return !flag[row][col - 1];
}

if (direction == UP) {
if (row - 1 < 0) {
return false;
} else return !flag[row - 1][col];
}

throw new RuntimeException("Impossible");
}
}

复杂度

时间复杂度:O(m*n)

空间复杂度:O(m*n)