算法练习——迷宫问题(Java)bfs广搜

问题描述:
小明置身于一个迷宫,请你帮小明找出从起点到终点的最短路程。
小明只能向上下左右四个方向移动。
输入
输入包含多组测试数据。输入的第一行是一个整数T,表示有T组测试数据。
每组输入的第一行是两个整数N和M(1<=N,M<=100)。
接下来N行,每行输入M个字符,每个字符表示迷宫中的一个小方格。
字符的含义如下:

‘S’:起点
‘E’:终点
‘-’:空地,可以通过
‘#’:障碍,无法通过

输入数据保证有且仅有一个起点和终点。
输出
对于每组输入,输出从起点到终点的最短路程,如果不存在从起点到终点的路,则输出-1。
样例输入
在这里插入图片描述
样例输出

9

题目原文https://www.dotcpp.com/oj/problem1672.html

题解:
解题思想:广度优先搜索(BFS)

public class Main{
	
    public static class Q{
        int x;
        int y;
        int dept;//当前步数
    }
	
	static int[][] move = {{0,1},{0,-1},{1,0},{-1,0}};

	static public void bfs(int[][] vis,int sx,int sy,LinkedList<Q> que,int gx,int gy,int n,int m,char[][] arr) {

		 Q q = new Q();
		 q.x = sx;
		 q.y = sy;
		 q.dept = 0;
		 que.add(q);//添加
		 int finish=0,result=0;
		 
		 while(que.size() != 0) {
			 Q first = que.poll(); //取出对头,并删除
			 if(first.x == gx && first.y == gy) {
				 finish =1;
				 result = first.dept;
				 break;
			 }
			 for(int i=0 ; i< 4 ; i++) {
				 int tx = first.x + move[i][0];
				 int ty = first.y + move[i][1];
				 //边界判定和判定是否走过
				 if(tx >=0 && tx <n && ty>=0 && ty<m && arr[tx][ty]!='#' && vis[tx][ty]==0) {
					 vis[tx][ty] = 1;
					 Q temp = new Q();
					 temp.x = tx;
					 temp.y = ty;
					 temp.dept=first.dept+1;
					 que.add(temp);
				 }
			 }
		 }//while
		 
		 //输出结果
         if (result==0) {
             System.out.println("-1");
         }else {
             System.out.println(result);
         }
	}
	public static void main(String[] args) {
		
		Scanner sc =new Scanner(System.in);
		int t = sc.nextInt();
		
		while( t-- > 0 ) {
			int n = sc.nextInt();
			int m = sc.nextInt();
			
			char[][] arr = new char[n][m];
			int sx=0,sy=0;
			int gx=0,gy=0;
			int[][] vis = new int[n][m];
			LinkedList<Q> que = new LinkedList<Q>();
			//
			for(int i=0 ; i < n ;i++) {
				String str=sc.next();
				for(int j=0 ; j< m  ;j++) {
					arr[i][j] = str.charAt(j);
					if(arr[i][j] == 'S') {
						sx=i;
						sy=j;
					}
					if(arr[i][j] == 'E') {
						gx=i;
						gy=j;
					}
				}
			}
			vis[sx][sy]=1;//标记开始坐标
			//广搜
			bfs(vis,sx,sy,que,gx,gy,n,m,arr);
		}//while
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值