求最短路径

该博客介绍了如何利用广度优先遍历解决从二维矩阵左上角到右下角的最短路径问题。通过设置队列和已访问数组,避免重复入队和环路导致的无限循环,确保找到最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:一个二维矩阵由0和1构成,求从左上角跑到右下角的最短路径。

解法:广度优先遍历,使用队列,队列中的元素如果不弹出的话,从队头到队尾是步数一次增加,

即:走一步可以到达的节点、走两步可以达到的节点、......

要设置已访问数组:目的是防止某个节点重复入队,因为如果某个元素被第二次访问,那此次走到它的步数一定大于第一次走到它的步数,所以这个节点不符合最短路径,所以没必要入队,而且这个算法的循环条件是队列不为空,如果可以重复入队,那么有可能出现队列永远不为空的情况,就比如说如果矩阵中存在环路。

package Array;

import java.util.LinkedList;
import java.util.Queue;

public class MinRoad {
    public static int minRoad(int[][] arr){
        if(arr == null || arr.length == 0 || arr[0].length == 0 || arr[0][0] == 0){
            return 0;
        }

        //寻找最小路径时使用广度优先遍历得将访问过的地方置为1,因为最先访问某点肯定是到达该点步数最少的。以后就即使有点
        //再来到该点,也不可能是最短路径1
        int[][] go = {{0,-1},{-1,0},{0,1},{1,0}};
        Queue<Node> qu = new LinkedList<>();
        Node node = new Node(0,0,1);
        qu.add(node);
        boolean[][] visited = new boolean[arr.length][arr[0].length];
        visited[0][0] = true;
        while(!qu.isEmpty()){
            Node tmp = qu.poll();
            int nowRow = tmp.row;
            int nowCol = tmp.col;
            int nowStep = tmp.step;
            if(nowRow == arr.length - 1 && nowCol == arr[0].length - 1){
                return nowStep;
            }
            for(int i = 0; i < 4; i++){
                int nextRow = nowRow + go[i][0];
                int nextCol = nowCol +go[i][1];
                if(nextRow >= 0 && nextRow < arr.length && nextCol >= 0 && nextCol < arr[0].length
                        && arr[nextRow][nextCol] == 1 && !visited[nextRow][nextCol]){
                    Node node1 = new Node(nextRow,nextCol,nowStep + 1);
                    qu.add(node1);
                    visited[nextRow][nextCol] = true;
                }
            }
        }
        return 0;
    }
    public static void main(String[] args){
        int[][] arr = {{1,0,1,1,1},{1,0,1,0,1},{1,1,1,0,1},{0,0,0,0,1}};
        System.out.print(minRoad(arr));
    }


}
class Node{
    int row;
    int col;
    int step;
    public Node(int row, int col, int step){
        this.row = row;
        this.col = col;
        this.step = step;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值