-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
80 lines (77 loc) · 2.11 KB
/
SpiralMatrix.java
File metadata and controls
80 lines (77 loc) · 2.11 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.yangchd.leetcode.medium;
import java.util.ArrayList;
import java.util.List;
/**
* @author yangchd 2018/10/11.
*
* 54. Spiral Matrix
* Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
*
* Example 1:
* Input:
* [
* [ 1, 2, 3 ],
* [ 4, 5, 6 ],
* [ 7, 8, 9 ]
* ]
* Output: [1,2,3,6,9,8,7,4,5]
*
* Example 2:
* Input:
* [
* [1, 2, 3, 4],
* [5, 6, 7, 8],
* [9,10,11,12]
* ]
* Output: [1,2,3,4,8,12,11,10,9,5,6,7]
*
*
*/
public class SpiralMatrix {
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<Integer>();
addInteger(matrix, 0, list);
return list;
}
private void addInteger(int[][] matrix, int time, List<Integer> list) {
int high = matrix.length - 2 * time;
if (high <= 0) {
return;
}
int width = matrix[0].length - 2 * time;
if (width <= 0) {
return;
}
if (high == 1) {
for (int line = 0; line < width; line++) {
list.add(matrix[time][time + line]);
}
return;
}
if (width == 1) {
for (int col = 0; col < high; col++) {
list.add(matrix[time + col][time]);
}
return;
}
// 上边
for (int top = 0; top < width - 1; top++) {
list.add(matrix[time][top + time]);
}
// 右边
for (int right = 0; right < high - 1; right++) {
list.add(matrix[right + time][width + time - 1]);
}
// 下边
for (int bottom = time + width - 1; bottom > time; bottom--) {
list.add(matrix[high + time - 1][bottom]);
}
// 左边
for (int left = high + time - 1; left > time; left--) {
list.add(matrix[left][time]);
}
addInteger(matrix, time + 1, list);
}
}
}