剑指 Offer 29. 顺时针打印矩阵

题目

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

1
2
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例2:

1
2
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

提示:

  • 0 <= matrix.length <= 100
  • 0 <= matrix[i].length <= 100

解法

解法一:

JAVA

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
public int[] spiralOrder(int[][] matrix) {
int row = matrix.length;
if (row == 0) {
return new int[0];
}
int col = matrix[0].length;
int[] res = new int[row * col];
int idx = 0;
int left = 0, top = 0, right = col - 1, bottom = row - 1;
while (true) {
//从左往右走
for (int i = left; i <= right; i++) {
res[idx++] = matrix[top][i];
}
if (++top > bottom) {
break;
}
//从上往下走
for (int i = top; i <= bottom; i++) {
res[idx++] = matrix[i][right];
}
if (--right < left) {
break;
}
//从右往左走
for (int i = right; i >= left; i--) {
res[idx++] = matrix[bottom][i];
}
if (--bottom < top) {
break;
}
//从下往上走
for (int i = bottom; i >= top; i--) {
res[idx++] = matrix[i][left];
}
if (++left > right) {
break;
}
}
return res;
}

解法二:

超时

Java

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
public int[] spiralOrder(int[][] matrix) {

if (Objects.isNull(matrix)) {
return null;
}

if (0 == matrix.length) {
return new int[]{};
}

int[][] directions = new int[4][2];
directions[0] = new int[]{0, 1}; // x++;
directions[1] = new int[]{1, 0}; // y++;
directions[2] = new int[]{0, -1}; // x--;
directions[3] = new int[]{-1, 0}; // y--

int[] result = new int[matrix.length * matrix[0].length];
int index = 0;
Set<String> visited = new HashSet<>(result.length);
int row = matrix.length;
int col = matrix[0].length;
int directionIndex = 0;
int r = 0;
int c = 0;
while (index < result.length) {
String p = r + "_" + c;
if (visited.contains(p)) {
continue;
}

result[index++] = matrix[r][c];

if (directionIndex == 0 && (c + 1) == col) {
// 转向
directionIndex = (directionIndex + 1) % 4;
} else if (directionIndex == 1 && (r + 1) == row) {
// 转向
directionIndex = (directionIndex + 1) % 4;
} else if (directionIndex == 2 && (c == 0 || visited.contains(p))) {
// 转向
directionIndex = (directionIndex + 1) % 4;
} else if (directionIndex == 3 && (r == 0 || visited.contains((r - 1) + "_" + c))) {
// 转向
directionIndex = 0;
}
r += directions[directionIndex][0];
c += directions[directionIndex][1];
visited.add(p);
}
return result;
}
0%