-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiralMatrix.kt
54 lines (53 loc) · 1.49 KB
/
SpiralMatrix.kt
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
package com.namanh.matrix
/**
* https://leetcode.com/problems/spiral-matrix
* Given an m x n matrix, return all elements of the matrix in spiral order.
*
* S1: Use top, bottom, left, right to limit for loop
* S2: Increase top, left, decrease bottom, right after for loop
*
* Time: O(m * n)
* Space: O(m * n)
*/
class SpiralMatrix {
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
val m = matrix.size
val n = matrix[0].size
val result = mutableListOf<Int>()
var index = 0
var left = 0
var right = n - 1
var top = 0
var bottom = m - 1
while (result.size < m * n) {
when (index % 4) {
0 -> {
for (i in left..right) {
result.add(matrix[top][i])
}
top++
}
1 -> {
for (i in top..bottom) {
result.add(matrix[i][right])
}
right--
}
2 -> {
for (i in right downTo left) {
result.add(matrix[bottom][i])
}
bottom--
}
3 -> {
for (i in bottom downTo top) {
result.add(matrix[i][left])
}
left++
}
}
index++
}
return result
}
}