https://leetcode.com/problems/spiral-matrix/
class Solution {
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
val answer = mutableListOf<Int>()
var startX = 0
var endX = matrix.size
var startY = 0
var endY = matrix[0].size
while (startX < endX && startY < endY) {
cycleMove(startX, startY, endX, endY, answer, matrix)
startX++
endX--
startY++
endY--
}
return answer
}
private fun cycleMove(
startX: Int,
startY: Int,
endX: Int,
endY: Int,
answer: MutableList<Int>,
matrix: Array<IntArray>
) {
// top
for (i in startY until endY) answer.add(matrix[startX][i])
// right
for (i in startX + 1 until endX) answer.add(matrix[i][endY - 1])
if (endX - 1 == startX || startY == endY - 1) return
// bottom
for (i in endY - 2 downTo startY) answer.add(matrix[endX - 1][i])
// left
for (i in endX - 2 downTo startX + 1) answer.add(matrix[i][startY])
}
}