Golang Walk-the-Spiral Solution


  • 0

    Starting from the upper left of the grid, walk counter-clockwise, allocating cells until we hit the end.
    Note there is a fix-up for the last cell in an odd-numbered n:

    func generateMatrix(n int) [][]int {
        // init the grid
        rows := make([][]int, n, n)
        for i := range rows {
            rows[i] = make([]int, n, n)
        }
        
        cellCount := 1
        ringOffset := 0
        cellMax := n*n
        for cellCount < cellMax {
            internalOffset := n-1-ringOffset
            // right
            for i := 0; i < internalOffset-ringOffset; i++ {
                rows[ringOffset][ringOffset+i] = cellCount
                cellCount++
            }
            // down
            for i := 0; i < internalOffset-ringOffset; i++ {
                rows[ringOffset+i][internalOffset] = cellCount
                cellCount++
            }
            // left
            for i := internalOffset; i > ringOffset; i-- {
                rows[internalOffset][i] = cellCount
                cellCount++
            }
            // up
            for i := internalOffset; i > ringOffset; i-- {
                rows[i][ringOffset] = cellCount
                cellCount++
            }
            ringOffset++
        }
        
        if n % 2 == 1 {
            rows[n/2][n/2] = cellCount
        }
        
        return rows
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.