计算在网格中从原点到特定点的最短路径长度

[[1,1,0,1],
 [1,0,1,0],
 [1,1,1,1],
 [1,0,1,1]]

题目描述:1 表示可以经过某个位置,求解从 (0, 0) 位置到 (tr, tc) 位置的最短路径长度。

 

采用bfs方法:



import java.util.*;

public class ShortestPath {

    public static void main(String[] args){

        /*
        grids: 测试用例
         */
        int[][] grids = {
                {1,1,0,1},
                {1,0,1,0},
                {1,1,1,1},
                {1,0,1,1}
        };
        int tr = 2;//target row
        int tc = 3;//target column
        int length = shortestPath(grids,tr,tc);//最短路径长度
        System.out.println(length);
    }


    /**
     * @param grids
     * @param tr : target row
     * @param tc : target column
     * @return : shorest path length
     */
    public static int shortestPath(int[][] grids,int tr,int tc){

        if(grids[0][0]==0 || grids[tr][tc]==0) return -1;

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

        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0,0});//(0,0)位置
        grids[0][0] = 0;//标记
        int num = 0;
        while(!queue.isEmpty()){
            num++;
            int size = queue.size();
            for(int i = 0;i<size;i++){
                int[] prev = queue.poll();
                if(tr==prev[0] && tc==prev[1]) return num-1;
                int prev_x = prev[0];
                int prev_y = prev[1];
                for(int[] direction:directions){
                    int newx = prev_x + direction[0];
                    int newy = prev_y + direction[1];
                    if(newx>=0 && newx<grids.length && newy>=0 && newy<grids[0].length){
                        queue.offer(new int[]{newx,newy});
                        grids[prev_x][prev_y] = 0;//标记
                    }
                }
            }
        }

        return -1;

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值