forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_54.java
70 lines (60 loc) · 1.59 KB
/
_54.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
/**
* 54. Spiral Matrix
*
* 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].
*/
public class _54 {
public static class Solution1 {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList();
int row = matrix.length;
if (row == 0) {
return result;
}
int rowStart = 0;
int rowEnd = matrix.length - 1;
int colStart = 0;
int colEnd = matrix[0].length - 1;
while (rowStart <= rowEnd && colStart <= colEnd) {
//traverse to the right
for (int j = colStart; j <= colEnd; j++) {
result.add(matrix[rowStart][j]);
}
rowStart++;
//traverse to the bottom
for (int i = rowStart; i <= rowEnd; i++) {
result.add(matrix[i][colEnd]);
}
colEnd--;
//only when rowStart <= rowEnd
//we'll traverse to the left
if (rowStart <= rowEnd) {
for (int j = colEnd; j >= colStart; j--) {
result.add(matrix[rowEnd][j]);
}
}
rowEnd--;
//only when colStart <= colEnd
//we'll traverse to the top
if (colStart <= colEnd) {
for (int i = rowEnd; i >= rowStart; i--) {
result.add(matrix[i][colStart]);
}
}
colStart++;
}
return result;
}
}
}