Skip to content

Commit 91ce568

Browse files
committed
refactor: spiral-matrix redundant checks
1 parent 721b1d2 commit 91ce568

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

spiral-matrix/minji-go.java

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,34 @@ class Solution {
99
public List<Integer> spiralOrder(int[][] matrix) {
1010
List<Integer> answer = new ArrayList<>();
1111
int lr = 0;
12-
int hr = matrix.length-1;
12+
int hr = matrix.length - 1;
1313
int lc = 0;
14-
int hc = matrix[0].length-1;
14+
int hc = matrix[0].length - 1;
1515

16-
while (lr<=hr && lc<=hc) {
17-
for(int c=lc; c<=hc && lr<=hr; c++) {
16+
while (lr <= hr && lc <= hc) {
17+
for (int c = lc; c <= hc; c++) {
1818
answer.add(matrix[lr][c]);
1919
}
2020
lr++;
2121

22-
for(int r=lr; r<=hr && lc<=hc; r++) {
22+
for (int r = lr; r <= hr; r++) {
2323
answer.add(matrix[r][hc]);
2424
}
2525
hc--;
2626

27-
for(int c=hc; c>=lc && lr<=hr; c--){
28-
answer.add(matrix[hr][c]);
27+
if (lr <= hr) {
28+
for (int c = hc; c >= lc; c--) {
29+
answer.add(matrix[hr][c]);
30+
}
31+
hr--;
2932
}
30-
hr--;
3133

32-
for(int r=hr; r>=lr && lc<=hc; r--){
33-
answer.add(matrix[r][lc]);
34+
if (lc <= hc) {
35+
for (int r = hr; r >= lr; r--) {
36+
answer.add(matrix[r][lc]);
37+
}
38+
lc++;
3439
}
35-
lc++;
3640
}
3741
return answer;
3842
}

0 commit comments

Comments
 (0)