DevPath

← All problems

Spiral Matrix Order

Medium matrix · simulation

Description

Return all elements of the matrix in spiral order, starting at the top-left and moving clockwise.

Constraints

1 <= rows, cols <= 100

Examples

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]

Output: [1,2,3,6,9,8,7,4,5]

Hints (1)
  • Maintain top, bottom, left and right boundaries and shrink them.

Solutions

Shrinking boundaries. · Time O(rows*cols) · Space O(1)

func spiralOrder(matrix [][]int) []int {
    out := []int{}
    top, bottom, left, right := 0, len(matrix)-1, 0, len(matrix[0])-1
    for top <= bottom && left <= right {
        for c := left; c <= right; c++ {
            out = append(out, matrix[top][c])
        }
        top++
        for r := top; r <= bottom; r++ {
            out = append(out, matrix[r][right])
        }
        right--
        if top <= bottom {
            for c := right; c >= left; c-- {
                out = append(out, matrix[bottom][c])
            }
            bottom--
        }
        if left <= right {
            for r := bottom; r >= top; r-- {
                out = append(out, matrix[r][left])
            }
            left++
        }
    }
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account