当前位置: 首页 > news >正文

LintCode第974题-求矩阵各节点的最短路径(以0为标准)

描述

给定一个由0和1组成的矩阵,求每个单元格最近的0的距离。
两个相邻细胞之间的距离是1。

给定矩阵的元素数不超过10,000。
在给定的矩阵中至少有一个0。
单元格在四个方向上相邻:上,下,左和右。

样例

例1:

输入:
[[0,0,0],
 [0,0,0],
 [0,0,0],
 [0,0,0],
 [0,0,0]]
输出:
[[0,0,0],
 [0,0,0],
 [0,0,0],
 [0,0,0],
 [0,0,0]]

例2:

 
输入:
[[0,1,0,1,1],
 [1,1,0,0,1],
 [0,0,0,1,0],
 [1,0,1,1,1],
 [1,0,0,0,1]]
输出:
[[0,1,0,1,2],
 [1,1,0,0,1],
 [0,0,0,1,0],
 [1,0,1,1,1],
 [1,0,0,0,1]]

本题主要考察广度优先搜索  

如需更快更简洁的算法请跳至思路2

思路1: 

思路1虽然也是广度优先搜索算法 但是是单源的广度优先搜索算法 即逐个继续遍历扩展其周围的元素

外层循环为每一层,内层循环为每一层的当前输入值

然后通过两个变量 path来记录路径的长度 队列来记录为未满足为0的位置索引 每次判断但凡队列的点相邻但凡没有一个符合条件就先让path+1  

然后记录所有不符合的点 直至循环出相邻有0的点 因为题目已经告知给定的矩阵至少有一个0

这就是每一个元素的遍历

最后将所有元素都这样执行一遍就可以得到每一个单元距离0的距离

即简要理解为针对每个 1 向外找最近 0

代码如下:

import java.util.*;

public class Solution {

    /**

     * @param matrix: a 0-1 matrix

     * @return: return a matrix

     */

    public int[][] updateMatrix(int[][] matrix) {

        int m = matrix.length;

        int n = matrix[0].length;

        int[][] pathMatrix = new int[m][n]; // 最终结果矩阵

        int path; // 当前单元格的路径

        Queue<int[]> integerQueue = new LinkedList<>(); // 存坐标的队列

        // 遍历每个单元格

        for (int i = 0; i < m; i++) {

            for (int j = 0; j < n; j++) {

                if (matrix[i][j] == 0) {

                    pathMatrix[i][j] = 0;

                } else {

                    // BFS 查找最近的 0

                    boolean[][] visited = new boolean[m][n];

                    integerQueue.clear();

                    integerQueue.offer(new int[]{i, j});

                    visited[i][j] = true;

                    path = 0;

                    boolean found = false;

                    while (!integerQueue.isEmpty() && !found) {

                        int size = integerQueue.size();

                        path++; // 每扩展一层,路径 +1

                        for (int q = 0; q < size; q++) {

                            int[] pos = integerQueue.poll();

                            int x = pos[0];

                            int y = pos[1];

                            int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}}; // 上下左右

                            for (int[] dir : dirs) {

                                int nx = x + dir[0];

                                int ny = y + dir[1];

                                if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visited[nx][ny]) {

                                    if (matrix[nx][ny] == 0) {

                                        pathMatrix[i][j] = path;

                                        found = true;

                                        break;

                                    } else {

                                        integerQueue.offer(new int[]{nx, ny});

                                        visited[nx][ny] = true;

                                    }

                                }

                            }

                            if (found) break;

                        }

                    }

                }

            }

        }

        return pathMatrix;

    }

}

时间复杂度为:O(m × n)^2

思路2:多源广度优先算法

同时从多个起点出发进行 BFS,也就是说:
不是一个一个来,而是全部起点一起“向外一层层扩散”

所有 0 一起扩散  访问一次就是最短路径 无冗余访问 即类似于同步水波扩散

需要注意的是 

m代表的是行数

n代表的是列数

代码如下:

public class Solution {

    public int[][] updateMatrix(int[][] matrix) {

        int m = matrix.length;

        int n = matrix[0].length;

        int[][] pathMatrix = new int[m][n];

        boolean[][] visited = new boolean[m][n];

        Queue<int[]> integerQueue = new LinkedList<>();

        //注意这里用LinkList 因为效率高 入队出队都是O(1) 而且LinkList实现了Deque,Deque又继承了队列,所以Queue可以直接用其实现类 LinkList.

        // 将所有为0的点入队,作为BFS的起点

        for (int y = 0; y < m; y++) {

            for (int x = 0; x < n; x++) {

                if (matrix[y][x] == 0) {

                    integerQueue.offer(new int[]{y, x});

                    visited[y][x] = true;

                }

            }

        }

        // 上下左右

        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        while (!integerQueue.isEmpty()) {

            int[] point = integerQueue.poll();

            int y = point[0], x = point[1];

            for (int[] dir : directions) {

                int newY = y + dir[0];

                int newX = x + dir[1];

                if (newY >= 0 && newY < m && newX >= 0 && newX < n && !visited[newY][newX]) {

                    pathMatrix[newY][newX] = pathMatrix[y][x] + 1;

                    visited[newY][newX] = true;

                    integerQueue.offer(new int[]{newY, newX});

                }

            }

        }

        return pathMatrix;

    }

}

 

http://www.dtcms.com/a/113336.html

相关文章:

  • 如何将本地更改的README文件同步到自己的GitHub项目仓库
  • OmniParser: 让大模型化身“电脑管家”
  • 洛谷 P3214 [HNOI2011] 卡农
  • 2.IO流的体系和字节输出流FileOutputStream的基本用法
  • macos 魔搭 模型下载 Wan-AI ComfyUI
  • L2-024 部落 #GPLT,并查集 C++
  • 智能驾驶中预测模块简介
  • 广州t11基地顺利完成交割,TCL华星技术产能双升级
  • 【java】Class.newInstance()
  • 硬币找零问题
  • 特征值与特征向量:从理论到应用的全面解析
  • Java类加载问题
  • STM32单片机入门学习——第16节: [6-4] PWM驱动LED呼吸灯PWM驱动舵机PWM驱动直流电机
  • 《AI大模型应知应会100篇》第4篇:Transformer架构深入浅出:大模型的基石
  • cadence17.4和16.6同时安装无法使用的问题
  • 关于图片分类任务的猜想 | 撰写论文 paper
  • .net多贸易公司借入借出归还设备进销存管理系统软件租金计算库存管理
  • M芯片,能运行普通应用程序的原架构虚拟机
  • Java的Selenium元素定位-xpath
  • LeetCode热题100记录-【二叉树】
  • 【Deep Reinforcement Learning Hands-On Third Edition】【第1章:什么是强化学习】
  • 《海空重力测量理论方法及应用》之一重力仪系统组成及工作原理(下)
  • qt designer 软件主题程序设计
  • Python精进系列:从 __name__ 开始了解 python 常见内置变量
  • synchronized 锁升级机制详解
  • ROS2 多机时间同步(Chrony配置简明指南)
  • docker本地部署anythingllm
  • C++重载运算符的本质
  • 将 DataFrame 中某一列的列表拆分成多个独立的列的方式
  • Linux上位机开发实践(做一专多能的方案提供者)