forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_54.java
95 lines (91 loc) · 3.03 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
public class _54 {
public static class Solution1 {
/**
* credit: https://leetcode.com/problems/spiral-matrix/discuss/20599/Super-Simple-and-Easy-to-Understand-Solution/185257
*/
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return new ArrayList<>();
}
int m = matrix.length;
int n = matrix[0].length;
List<Integer> result = new ArrayList();
int left = 0;
int right = n - 1;
int top = 0;
int bottom = m - 1;
while (result.size() < m * n) {
for (int j = left; j <= right && result.size() < m * n; j++) {
result.add(matrix[top][j]);
}
top++;
for (int i = top; i <= bottom && result.size() < m * n; i++) {
result.add(matrix[i][right]);
}
right--;
for (int j = right; j >= left && result.size() < m * n; j--) {
result.add(matrix[bottom][j]);
}
bottom--;
for (int i = bottom; i >= top && result.size() < m * n; i--) {
result.add(matrix[i][left]);
}
left++;
}
return result;
}
}
public static class Solution2 {
/**
* My completely original solution on 12/29/2021.
*/
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<>();
int m = matrix.length;
int n = matrix[0].length;
int direction = 0;
int total = m * n;
int j = 0;
int i = 0;
int lowerRow = 0;
int lowerCol = 0;
while (ans.size() < total) {
for (; i < m && i >= lowerRow && j < n && j >= lowerCol; ) {
ans.add(matrix[i][j]);
if (direction == 0) { //east
j++;
} else if (direction == 1) { //south
i++;
} else if (direction == 2) { //west
j--;
} else {
i--; //north
}
}
if (direction == 0) {
i++;
j--;
} else if (direction == 1) {
j--;
i--;
} else if (direction == 2) {
j++;
i--;
lowerRow++;
m--;
} else {
i++;
j++;
lowerCol++;
n--;
}
direction++;
direction %= 4;
}
return ans;
}
}
}