Skip to content

Commit 1cd8740

Browse files
authored
Merge pull request neetcode-gh#639 from sharansalian/main
Add 54-Spiral-Matrix.kt
2 parents 3bb1935 + 22eea61 commit 1cd8740

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

kotlin/54-Spiral-Matrix.kt

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package kotlin
2+
3+
4+
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
5+
var res = mutableListOf<Int>()
6+
var top = 0
7+
var right = matrix.first().size
8+
var left = 0
9+
var bottom = matrix.size
10+
11+
while (top < bottom && left < right) {
12+
13+
//get every i in the top row
14+
for (i in left until right) {
15+
res.add(matrix[top][i])
16+
}
17+
top += 1
18+
19+
// get every i in the right col
20+
for (i in top until bottom) {
21+
res.add(matrix[i][right - 1])
22+
}
23+
right -= 1
24+
25+
if (!(left < right && top < bottom)) {
26+
break
27+
}
28+
29+
//get every i in the bottom row
30+
for (i in right - 1 downTo left) {
31+
res.add(matrix[bottom - 1][i])
32+
}
33+
bottom -= 1
34+
35+
//get every i in the left col
36+
for (i in bottom - 1 downTo top) {
37+
res.add(matrix[i][left])
38+
}
39+
40+
left += 1
41+
42+
}
43+
44+
return res
45+
46+
}
47+
48+
fun main() {
49+
val matrix = arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9))
50+
println(spiralOrder(matrix))
51+
}

0 commit comments

Comments
 (0)