Leetcode 54 螺旋矩阵/59 螺旋矩阵II Golang

54 螺旋矩阵

func spiralOrder(matrix [][]int) []int {
    if len(matrix) == 0 {
        return []int{}
    }
    R, C := len(matrix), len(matrix[0])
    visited := make([][]int, R)
    for r := 0; r < R; r++ {
        visited[r] = make([]int, C)
    }
    N := R * C
    res := make([]int, N)
    r, c, dr, dc := 0, 0, 0, 1
    for i := 0; i < N; i++ {
        res[i] = matrix[r][c]
        visited[r][c] = 1
        if visited[fix(dr+r, R) % R][fix(dc+c, C) % C] == 1 {
            dr, dc = dc, -dr
        }
        r, c = r + dr, c + dc
    }
    return res
}

func fix(x, n int) int {
    if x < 0 {
        return x + n
    }
    return x
}

59 螺旋矩阵II

func generateMatrix(n int) [][]int {
    mtx := make([][]int, n)
    for r := 0; r < n; r++ {
        mtx[r] = make([]int, n)
    }
    r, c, dr, dc := 0, 0, 0, 1
    
    for i := 0; i < n*n; i++ {
        mtx[r][c] = i + 1

        if mtx[fix(r+dr, n) % n][fix(c+dc, n) % n] > 0 {
            dr, dc = dc, -dr
        }
        r, c = r + dr, c + dc
    }
    
    return mtx
}

func fix(x, n int) int {
    if x < 0{
        return x + n
    }
    return x
}

 

你可能感兴趣的:(算法,golang)