Acwing---844. 走迷宫(Java)_BFS求最优解

844. 走迷宫

  • ①. 题目
  • ②. 思路
  • ③. 学习点
  • ④. 代码实现

原题链接

①. 题目

Acwing---844. 走迷宫(Java)_BFS求最优解_第1张图片

输入样例

5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

②. 思路

  • 求最优解,dfs可以搜到,但是BFS能直接搜出最优解,深搜一般没有框架,宽搜有。深度搜索可以保证搜到,但不能保证最短。宽度(广度)优先搜索:BFS不考虑结果的可能位置,彻底地搜索整张图,即先找所有距离为1,再找所有距离为2,需额外的距离数组判断是否遍历过和记录距离、即宽度;展开节点而得到的子节点都会被加进一个先进先出的队列,直到找到结果为止。

③. 学习点

BFS求最优解

④. 代码实现

import java.io.*;
import java.util.*;

public class _844_走迷宫_BFS {
     
	public static void main(String[] args) throws IOException {
     
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] s1 = br.readLine().split(" ");
        int  n = Integer.valueOf(s1[0]);
        int m = Integer.valueOf(s1[1]);
		int[][] arr=new int[n][m];
		for (int i = 0; i < n; i++) {
     
			 String[] s = br.readLine().split(" ");
			for (int j = 0; j < m; j++) {
     
				arr[i][j]=Integer.parseInt(s[j]);
			}
		}
		
		Queue<int[]> queue=new LinkedList<>();
		int[] dx= {
     -1,0,1,0},dy= {
     0,1,0,-1};
		queue.offer(new int[] {
     0,0});
		int res=0;
		int x=0,y=0;
		int[][] d=new int[n][m];
		while(!queue.isEmpty()) {
     
			int[] poll = queue.poll();
			x=poll[0];
			y=poll[1];
			//BFS 优先输出最短路径
			//当到达最后一个点 直接跳出打印
			if(x==n-1 &&y==m-1) {
     
				break;
			}
			for(int i=0;i<4;i++) {
     
				int a=x+dx[i];
				int b=y+dy[i];
				if(a>=0 && a<n&&b>=0&& b<m && arr[a][b]==0&& d[a][b]==0) {
     
					queue.offer(new int[] {
     a,b});
					d[a][b]=d[x][y]+1;
				}
			}
		}
		System.out.print(d[n-1][m-1]);
	}

}

Acwing---844. 走迷宫(Java)_BFS求最优解_第2张图片

你可能感兴趣的:(#,Acwing刷题)