问题描述
有一个方格迷宫,我们可以将它看作一个n*m的矩阵,每个方格表示一个房间,方格中有数字0和1,数字0表示该房间是空的,可以顺利通过,数字1表示该房间有怪兽,不能通过。
一开始何老板位于左上角的方格(坐标[1,1]位置),他要走到右下角的出口(坐标[n,m]位置),每一步何老板可以往上、下、左、右走。
他想知道最少需要几步就可以走出迷宫?
输入格式
第一行,两个整数n和m
接下来是一个有数字0和1构成的n*m的矩阵,表示迷宫
输出格式
一个整数,表示最小步数。若无解,输出-1
样例输入
4 5
0 0 0 0 0
0 1 1 1 0
0 1 0 0 0
0 0 0 1 0
样例输出
7
提示
1<=n,m<=20
DFS搜索
#include<bits/stdc++.h>
using namespace std;
int n,m,a[25][25],c[25][25],z[4][2]={{0,1},{0,-1},{1,0},{-1,0}};;
struct jgt{
int x,y;
};
queue<jgt> t;
void dg(int x,int y){
jgt s;
s.x=x;
s.y=y;
t.push(s);
while(!t.empty()){
jgt w=t.front();
t.pop();
int cx=w.x,cy=w.y;
for(int i=0;i<4;i++){
int xx=cx+z[i][0],yy=cy+z[i][1];
if(xx==n&&yy==m){
cout<<c[cx][cy]+1;
return;
}
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&a[xx][yy]==0){
a[xx][yy]=1;
c[xx][yy]=c[cx][cy]+1;
w.x=xx;
w.y=yy;
t.push(w);
}
}
}
printf("-1");
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%d",&a[i][j]);
}
}
dg(1,1);
return 0;
}