给定一个n*m的二维整数数组,用来表示一个迷宫,数组中只包含0或1,其中0表示能够走的路,1表示不可经过的墙壁。java
最初,有一我的位于左上角(1, 1)处,已知该人每次能够向上、下、左、右任意一个方向移动一个位置。数组
请问,该人从左上角移动至右下角(n, m)处,至少须要移动多少次。ui
数据保证(1, 1)处和(n, m)处的数字为0,且必定至少存在一条通路。this
输入格式
第一行包含两个整数n和m。spa
接下来n行,每行包含m个整数(0或1),表示完整的二维数组迷宫。code
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。xml
数据范围
1≤n,m≤1001≤n,m≤100blog
输入样例:
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
输出样例:
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(); } }