Skip to content

Latest commit

 

History

History
36 lines (30 loc) · 1.01 KB

54.spiral-matrix.md

File metadata and controls

36 lines (30 loc) · 1.01 KB
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
    val elements = mutableListOf<Int>()
    val m = matrix.size
    val n = matrix[0].size
    val directions = arrayOf(
        intArrayOf(0, 1),   // Right
        intArrayOf(1, 0),   // Down
        intArrayOf(0, -1),  // Left
        intArrayOf(-1, 0)   // UP
    )
    
    val visited = Array(m) { _ -> BooleanArray(n) }
    var direction = 0
    var row = 0
    var col = 0
    while (elements.size < m * n) {
        elements.add(matrix[row][col])
        visited[row][col] = true
        
        val newRow = row + directions[direction][0]
        val newCol = col + directions[direction][1]
        
        if (newRow < 0 || newRow >= m || newCol < 0 || newCol >= n || visited[newRow][newCol]) {
            direction = (direction + 1) % directions.size
        }
        
        row += directions[direction][0]
        col += directions[direction][1]
    }
    
    return elements
}