Skip to content

Commit 5bc4b26

Browse files
author
Jeongwon Na
committed
solution: spiral matrix
1 parent 621834d commit 5bc4b26

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

spiral-matrix/njngwn.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Time Complexity: O(m+n), m: matrix.length, n: matrix[0].length
2+
// Space Complexity: O(m*n), m: matrix.length, n: matrix[0].length, because of arraylist for output
3+
class Solution {
4+
public List<Integer> spiralOrder(int[][] matrix) {
5+
int rowMin = 0;
6+
int rowMax = matrix.length-1;
7+
int colMin = 0;
8+
int colMax = matrix[0].length-1;
9+
10+
ArrayList<Integer> orderedElements = new ArrayList<>();
11+
12+
while (rowMin <= rowMax && colMin <= colMax) {
13+
// left to right
14+
for (int col = colMin; col <= colMax; ++col) {
15+
orderedElements.add(matrix[rowMin][col]);
16+
}
17+
rowMin++;
18+
19+
// top to bottom
20+
for (int row = rowMin; row <= rowMax; ++row) {
21+
orderedElements.add(matrix[row][colMax]);
22+
}
23+
colMax--;
24+
25+
// right to left
26+
if (rowMin <= rowMax) {
27+
for (int col = colMax; col >= colMin; --col) {
28+
orderedElements.add(matrix[rowMax][col]);
29+
}
30+
}
31+
rowMax--;
32+
33+
// bottom to top
34+
if (colMin <= colMax) {
35+
for (int row = rowMax; row >= rowMin; --row) {
36+
orderedElements.add(matrix[row][colMin]);
37+
}
38+
}
39+
colMin++;
40+
}
41+
42+
return orderedElements;
43+
}
44+
}

0 commit comments

Comments
 (0)