给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
val row = matrix.size
val col = matrix[0].size
val list = mutableListOf<Int>()
val direction = listOf(intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(-1, 0))
val visited = Array(row) { BooleanArray(col) { false } }
var dIndex = 0
var curRow = 0
var curCol = 0
while (list.size < row * col) {
list.add(matrix[curRow][curCol])
visited[curRow][curCol] = true
val nextRow = curRow + direction[dIndex][0]
val nextCol = curCol + direction[dIndex][1]
if (nextRow >= row || nextRow < 0 ||
nextCol >= col || nextCol < 0 ||
visited [nextRow][nextCol]
) {
dIndex = (dIndex + 1) % 4
}
curRow += direction[dIndex][0]
curCol += direction[dIndex][1]
}
return list
}