NOTE

Spiral Matrix

Traverse a matrix in clockwise spiral order.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Given an m-row, n-column matrix, return all elements of the matrix in clockwise spiral order.

2. Approach

Shrink the range after traversing one loop.

3. Implementation

func spiralOrder(matrix [][]int) []int {
    if len(matrix) == 0 {
        return nil
    }

    row := -1
    col := -1
    minRow := -1
    minCol := -1
    maxRow := len(matrix)
    maxCol := len(matrix[0])
    res := make([]int, 0, maxRow*maxCol)
    for len(res) != cap(res) {
        row++
        col++
        minRow++
        minCol++
        maxCol--
        maxRow--
        visit(matrix, row, col,minRow,minCol, maxRow, maxCol, &res)
    }
    return res
}

func visit(matrix [][]int, row int, col int, minRow int, minCol int, maxRow int, maxCol int, res*[]int) {
    for col <= maxCol {
        *res = append(*res, matrix[row][col])
        if len(*res) == cap(*res) {
            return
        }
        col++
    }
    col--
    row++
    for row <= maxRow {
        *res = append(*res, matrix[row][col])
        if len(*res) == cap(*res) {
            return
        }
        row++
    }
    row--
    col--
    for col >= minCol {
        *res = append(*res, matrix[row][col])
        if len(*res) == cap(*res) {
            return
        }
        col--
    }
    col++
    row--
    for row > minRow {
        *res = append(*res, matrix[row][col])
        if len(*res) == cap(*res) {
            return
        }
        row--
    }
}

4. References

54. Spiral Matrix - LeetCode

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub