Skip to content

Commit c034d88

Browse files
committed
[week6](gmlwls96) Spiral Matrix
1 parent cad04fa commit c034d88

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

spiral-matrix/gmlwls96.kt

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
// 시간 : O(y*x), 공간 : O(1)
3+
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
4+
val result = mutableListOf<Int>()
5+
if (matrix.isEmpty() || matrix[0].isEmpty()) return result
6+
7+
var top = 0
8+
var bottom = matrix.size - 1
9+
var left = 0
10+
var right = matrix[0].size - 1
11+
12+
while (top <= bottom && left <= right) {
13+
for (i in left..right) result.add(matrix[top][i])
14+
top++
15+
for (i in top..bottom) result.add(matrix[i][right])
16+
right--
17+
if (top <= bottom) {
18+
for (i in right downTo left) result.add(matrix[bottom][i])
19+
bottom--
20+
}
21+
if (left <= right) {
22+
for (i in bottom downTo top) result.add(matrix[i][left])
23+
left++
24+
}
25+
}
26+
27+
return result
28+
}
29+
}

0 commit comments

Comments
 (0)