forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Matrix.java
48 lines (45 loc) · 1.6 KB
/
Spiral Matrix.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
// Runtime: 0 ms (Top 100.00%) | Memory: 42.2 MB (Top 37.48%)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
int upper_bound = 0, lower_bound = m - 1;
int left_bound = 0, right_bound = n - 1;
List<Integer> res = new LinkedList<>();
// res.size() == m * n to go through the whole matrix
while (res.size() < m * n) {
if (upper_bound <= lower_bound) {
// from left to right on the top
for (int j = left_bound; j <= right_bound; j++) {
res.add(matrix[upper_bound][j]);
}
// move the upper bound down
upper_bound++;
}
if (left_bound <= right_bound) {
// traveral from up to dwon on the right side
for (int i = upper_bound; i <= lower_bound; i++) {
res.add(matrix[i][right_bound]);
}
// move the right bound left
right_bound--;
}
if (upper_bound <= lower_bound) {
// traveral from rigth to left on the bottom side
for (int j = right_bound; j >= left_bound; j--) {
res.add(matrix[lower_bound][j]);
}
// move the lower bound up
lower_bound--;
}
if (left_bound <= right_bound) {
//traveral from down to up on the left side
for (int i = lower_bound; i >= upper_bound; i--) {
res.add(matrix[i][left_bound]);
}
// move the left bound rigth
left_bound++;
}
}
return res;
}
}