LeetCode1030. 距离顺序排列矩阵单元格-Java&Go-BFS

  • 算法
    • 1.广度优先搜素
    • 2.队列实现广度优先搜索,visited数组记录已访问坐标
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
    int[][] result = new int[R*C][2];
    int i = 0;

    boolean[][] visited = new boolean[R][C];
    visited[r0][c0] = true;

    Queue<int[]> queue = new LinkedList<>();
    queue.offer(new int[]{r0, c0});
    while (!queue.isEmpty()) {
        int size = queue.size();
        while (size-- > 0) {
            int[] curr = queue.poll();
            result[i++] = curr;
            if (curr[0] - 1 >= 0 && !visited[curr[0]-1][curr[1]]) {
                queue.offer(new int[]{curr[0]-1, curr[1]});
                visited[curr[0]-1][curr[1]] = true;
            }
            if (curr[0] + 1 < R && !visited[curr[0]+1][curr[1]]) {
                queue.offer(new int[]{curr[0]+1, curr[1]});
                visited[curr[0]+1][curr[1]] = true;
            }
            if (curr[1] - 1 >= 0 && !visited[curr[0]][curr[1]-1]) {
                queue.offer(new int[]{curr[0], curr[1]-1});
                visited[curr[0]][curr[1]-1] = true;
            }
            if (curr[1] + 1 < C && !visited[curr[0]][curr[1]+1]) {
                queue.offer(new int[]{curr[0], curr[1]+1});
                visited[curr[0]][curr[1]+1] = true;
            }
        }
    }
    return result;
}
func allCellsDistOrder(R int, C int, r0 int, c0 int) [][]int {
    result := make([][]int, R * C)
    i := 0

    visited := make([][]bool, R)
    for i := range visited {
        visited[i] = make([]bool, C)
    }
    visited[r0][c0] = true

    l := list.New()
    l.PushBack([]int{r0, c0})
    for l.Len() > 0 {
        size := l.Len()
        for size > 0 {
            curr := l.Remove(l.Front())
            p := curr.([]int)
            result[i] = p
            i++
            if p[0] - 1 >= 0 && !visited[p[0] - 1][p[1]] {
                l.PushBack([]int{p[0] - 1, p[1]})
                visited[p[0] - 1][p[1]] = true
            }
            if p[0] + 1 < R && !visited[p[0] + 1][p[1]] {
                l.PushBack([]int{p[0] + 1, p[1]})
                visited[p[0] + 1][p[1]] = true
            }
            if p[1] - 1 >= 0 && !visited[p[0]][p[1] - 1] {
                l.PushBack([]int{p[0], p[1] - 1})
                visited[p[0]][p[1] - 1] = true
            }
            if p[1] + 1 < C && !visited[p[0]][p[1] + 1] {
                l.PushBack([]int{p[0], p[1] + 1})
                visited[p[0]][p[1] + 1] = true
            }
            size--
        }
    }
    return result
}
LeetCode题解 文章被收录于专栏

测试

全部评论

相关推荐

Pandaileee:校友加油我现在也只有一个保底太难了
点赞 评论 收藏
分享
爱看电影的杨桃allin春招:我感觉你在炫耀
点赞 评论 收藏
分享
11-01 08:48
门头沟学院 C++
伤心的候选人在吵架:佬你不要的,能不能拿户口本证明过户给我。。球球了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务