542.01 矩阵
542.01矩阵
题解
思路
BFS 从0进队列,弹出之后计算上下左右的结果,将上下左右重新进队列进行二层操作 0 0 0 0 0 x 0 0 x x x 0 0 x 0 0 0 0 0 0 0 1 0 0 1 x 1 0 0 1 0 0 0 0 0 0 0 1 0 0 1 2 1 0 0 1 0 0
代码
package main func updateMatrix(mat [][]int) [][]int { var queue [][]int for i := 0; i < len(mat); i++ { for j := 0; j < len(mat[i]); j++ { if mat[i][j] == 0 { point := []int{i, j} queue = append(queue, point) } else { mat[i][j] = -1 } } } dir := [][]int{{0, 1}, {0, -1}, {-1, 0}, {1, 0}} for len(queue) != 0 { //pop point := queue[0] queue = queue[1:] //bfs for _, v := range dir { x := point[0] + v[0] y := point[1] + v[1] //如果没有超出边界并且是-1的那些数 if x >= 0 && x < len(mat) && y >= 0 && y < len(mat[0]) && mat[x][y] == -1 { mat[x][y] = mat[point[0]][point[1]] + 1 queue = append(queue, []int{x, y}) } } } return mat }