844. Maze (bfs template)

Given an n * m two-dimensional array of integers, used to represent a maze, the array contains only 0 or 1, where 0 represents the way to go, 1 denotes impassable wall.

Initially, there is a person at the top left (1, 1), known to each person can be moved up, down, left, and right shifted by one position in any direction.

Will the person moves from the upper left to the lower right corner (n, m) at least needs to be moved many times.

To ensure that digital data at (1, 1) and (n, m) is at 0, and there must be at least one passageway.

Input Format

The first line contains two integers n and m.

Subsequently n rows, each row containing m integers (0 or 1), a two-dimensional array represents the complete maze.

Output Format

Output an integer, represents the minimum number of moves from the upper left to the lower right corner of the mobile.

data range

1n,m1001≤n,m≤100

Sample input:

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

Sample output:

8

bfs一般用于求最短路径/最少次数这种问题,每个状态的变化权值必须一样

代码:
import java.util.ArrayDeque;
import java.util.Scanner;
class Node{
     int x;
     int y;
     int step;
     public Node(int x,int y,int step){
           this.x=x; this.y=y; this.step=step;
     }
}
public class Main{
        static final int N=105;
        static int n,m;
        static int map[][]=new int[N][N];
        static int dx[]={1,-1,0,0};
        static int dy[]={0,0,1,-1};
        static ArrayDeque<Node> q=new ArrayDeque<>();
        static void bfs(){
                q.offer(new Node(0,0,0));
                while(!q.isEmpty()){
                        Node t=q.poll();
                        if(t.x==n-1 && t.y==m-1){
                                System.out.println(t.step);
                                break;
                        }
                        for(int i=0;i<4;i++){
                                int xx=t.x+dx[i];
                                int yy=t.y+dy[i];
                                if(xx<0 || yy<0 || xx>=n || yy>=m || map[xx][yy]==1) continue;
                                map[xx][yy]=1;
                                q.offer(new Node(xx,yy,t.step+1));
                        }
                }
        }
        public static void main(String[] args) {
                Scanner scan=new Scanner(System.in);
                n=scan.nextInt();
                m=scan.nextInt();
                for(int i=0;i<n;i++)
                    for(int j=0;j<m;j++)
                        map[i][j]=scan.nextInt();
                bfs();
        }
}

 

Guess you like

Origin www.cnblogs.com/qdu-lkc/p/12242202.html