迷宫的最短路径------队列

这篇博客探讨了一种算法思路,通过广度优先搜索(BFS)来寻找二维网格中从起点到终点的最短路径。输入是一组二进制数据,表示网格中的可行走区域,算法会遍历所有可能的方向,并使用队列进行存储和标记,避免重复访问。当找到出口时,返回路径字符串表示最短路径。

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

题目:

输入数据:
6 8
0 1 0 1 0 0 0 1
1 0 0 1 1 0 1 0
0 1 1 0 0 1 1 1
1 0 0 1 1 0 0 1
1 0 0 0 1 1 0 1
0 1 1 1 0 0 0 0

输出数据:
(0,0)->(1,1)->(1,2)->(2,3)->(2,4)->(3,5)->(4,6)->(5,7)

算法思路:将所有方向用dir数组装起来,将顶点加入队列,进入循环,循环出口:为x,y坐标等于设置的出口坐标,每次将各个方位的坐标加入队列中并做上标记(防止重复走,减少计算量),最先到达循环出口的即为最小路径.

import java.util.LinkedList;
import java.util.Scanner;


public class Main {
	//能走的各个方向
	static int dir[][] = {{-1,0},{0,-1},{1,0},{0,1},{1,1},{1,-1},{-1,1},{-1,-1}};
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Scanner cin = new Scanner(System.in);
		while(cin.hasNext()){
			int n=cin.nextInt();
			int m=cin.nextInt();
			boolean locate [][] = new boolean[n][m];
			for(int i=0;i<n;i++){
				for(int j=0;j<m;j++){
					int judge = cin.nextInt();
					if(judge == 1){
						locate[i][j] = true;
					}
				}
			}
			System.out.println(find(n,m,locate));
		}
	}
	public static String find(int n,int m,boolean locate [][]){
		LinkedList<Data> q = new LinkedList<Data>();
		q.add(new Data(0,0,""));
		locate [0][0] = true;
		while(!q.isEmpty()){
			Data t = q.poll();
			if(t.x==n-1 && t.y==m-1){
				return t.str;
			}else{
				for(int i=0;i<dir.length;i++){
					int xx = t.x + dir[i][0];
					int yy = t.y + dir[i][1];
					if(xx>=0 && xx <n && yy >=0 && yy<m && locate[xx][yy]==false){
						q.add(new Data(xx,yy,t.str));
						locate[xx][yy] = true;
					}
				}
			}
		}
		return null;
	}

}
class Data{
	int x;
	int y;
	String str;
	public Data(int x, int y,String str) {
		super();
		this.x = x;
		this.y = y;
		if(x==0&&y==0){
			this.str = "("+x+","+y+")";
		}else{
			this.str = str+"->("+x+","+y+")";
		}
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值