给定一个迷宫,问是否可以走出去,入口固定为左上角,出口为右下角,且只能上下左右直线移动。
#include<bits/stdc++.h>
#define inf -0x3f3f3f3f
#define maxsize 100
using namespace std;
bool bfs();
void init(int n,int m);
struct graph
{
int x;
int y;
};
int n,m;///迷宫的行数和列数
int g[maxsize][maxsize];
bool check[maxsize][maxsize];
int main()
{
memset(g,inf,sizeof(g));
cin>>n>>m;
init(n,m);
if(bfs()) cout<<"yes"<<endl;
else cout<<"no"<<endl;
return 0;
}
void init(int n,int m)///初始化迷宫
{
for(int i = 1;i <= n; i++)
for(int j = 1;j <= m; j++)
cin>>g[i][j];
}
bool bfs()
{
queue<graph> q;
graph v;
v.x = v.y = 1;
check[v.x][v.y] = true;
q.push(v);
while(!q.empty())
{
graph node = q.front();
q.pop();
if(node.x==n&&node.y==m)
return true;
if(g[node.x-1][node.y]>0&&(!check[node.x-1][node.y]))///上移
{
graph w;
w.x = node.x-1;
w.y = node.y;
check[w.x][w.y] = true;
q.push(w);
}
if(g[node.x+1][node.y]>0&&(!check[node.x+1][node.y]))///下移
{
graph w;
w.x = node.x+1;
w.y = node.y;
check[w.x][w.y] = true;
q.push(w);
}
if(g[node.x][node.y-1]>0&&(!check[node.x][node.y-1]))///左移
{
graph w;
w.x = node.x;
w.y = node.y-1;
check[w.x][w.y] = true;
q.push(w);
}
if(g[node.x][node.y+1]>0&&(!check[node.x][node.y+1]))///下移
{
graph w;
w.x = node.x;
w.y = node.y+1;
check[w.x][w.y] = true;
q.push(w);
}
}
return false;
}
/*5 5
1 0 0 0 1
1 0 0 1 0
1 1 0 1 1
0 1 1 0 0
0 0 0 1 1
no
4 7
1 1 1 0 1 0 0
1 0 1 1 0 1 0
1 1 0 1 1 1 0
0 0 0 0 0 1 1
yes
*/