【笔试】Java实现计算在网格中从原点到特定点的最短路径长(BFS)

本文介绍了一种使用广度优先搜索(BFS)算法在二维网格中寻找从原点到指定点的最短路径的方法。通过队列和标记机制,算法能够有效地避免重复遍历并找到最短路径。

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

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

实现 BFS 时需要考虑以下问题:

  • 队列:用来存储每一轮遍历得到的节点;
  • 标记:对于遍历过的节点,应该将它标记,防止重复遍历。
	[[1,1,0,1],
	 [1,0,1,0],
	 [1,1,1,1],
	 [1,0,1,1]]

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

public class FindminPathLength{
	public static void main(String[] args) {
		int [][]grids= {{1,1,0,1},
						{1,0,1,0},
						{1,1,1,1},
						{1,0,1,1}};
		int res=minPathLength(grids, 4, 1);
		System.out.println(res);
	}
	public static int minPathLength(int[][] grids, int tr, int tc) {
	    final int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
	    final int m = grids.length, n = grids[0].length;
	    Queue<Pair<Integer, Integer>> queue = new LinkedList<>();
	    queue.add(new Pair<>(0, 0));
	    int pathLength = 0;
	    while (!queue.isEmpty()) {
	        int size = queue.size();
	        pathLength++;
	        while (size-- > 0) {
	            Pair<Integer, Integer> cur = queue.poll();
	            int cr = cur.getKey(), cc = cur.getValue();
	            grids[cr][cc] = 0; // 标记
	            for (int[] d : direction) {
	                int nr = cr + d[0], nc = cc + d[1];
	                if (nr < 0 || nr >= m || nc < 0 || nc >= n || grids[nr][nc] == 0) {
	                    continue;
	                }
	                if (nr == tr && nc == tc) {
	                    return pathLength;
	                }
	                queue.add(new Pair<>(nr, nc));
	            }
	        }
	    }
	    return -1;
	}
}
class Pair<K,V>{
	K key;
	V value;
	public Pair(K key,V value) {
		this.key=key;
		this.value=value;
	}	
	public int getKey() {
		return (int) this.key;
	}	
	public int getValue() {
		return (int) this.value;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小台

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值