一个由,0,1构成的 n∗n 的迷宫,给定入口和出口,问是否有通路走出迷宫
通路的意思是周围的8个方向,即上、下、左、右、左上、左下、右上、右下
输入格式
第一行1个正整数 n 表示迷宫规格 (2⩽n⩽100)
第二行有4个正整数x1,y1,x1,y2,分别表示入口坐标(x1,y1)和出口坐标(x2,y2),x为行坐标、y为列坐标,编号从0开始到n−1,输入保证0⩽x<n且0⩽y<n,且输入保证入口和出口处不为障碍物、入口与出口不重合
后面 n 行,每行 n 个数(为1或0,1表示障碍物,0表示可通行),数与数之间没有分隔符
输出格式
输出一行, yes 表示有通路,no 表示无通路
样例
input
2 0 1 1 1 00 10
output
yes
input
5 4 2 1 4 01010 11100 11111 10011 10001
output
no
提示
通路的意思是周围的8个方向,即上、下、左、右、左上、左下、右上、右下
思路:
使用循环对每个方向进行遍历,只要有成功的就返回值
#include <iostream>
using namespace std;
struct MOVE{int a;int b;};
struct STACK{int x,y,d;};
char maze[100][100];
int mark[100][100];
STACK route[100*100];
MOVE mv[8];
int top;
int n;
int getmap(int x1,int y1,int x2,int y2)
{
int now_x,now_y,next_x,next_y;
int dir;
if(maze[x1][y1]!='0' || maze[x2][y2]!='0')
return 1;
route[0].x=x1;
route[0].y=y1;
route[0].d=-1;
top=1;
mark[x1][y1]=1;
while(top>0)
{
top--;
now_x=route[top].x;
now_y=route[top].y;
dir=route[top].d;
while(dir<7)
{
dir++;
next_x=now_x+mv[dir].a;
next_y=now_y+mv[dir].b;
if(next_x<0 || next_y<0 || next_x>=n|| next_y>=n)
continue;
if(next_x==x2 && next_y==y2)
{
return 0;
}
if(maze[next_x][next_y]=='0' && mark[next_x][next_y]==0)
{
mark[next_x][next_y]=1;
route[top].x=now_x;
route[top].y=now_y;
route[top].d=dir;
now_x=next_x;
now_y=next_y;
dir=-1;
top++;
}
}
}
return 1;
}
int main()
{
cin>>n;
int x1,x2,y1,y2;
cin>>x1>>y1>>x2>>y2;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
mark[i][j]=0;
cin>>maze[i][j];
}
mv[0].a = -1; mv[0].b = 0;
mv[1].a = -1; mv[1].b = 1;
mv[2].a = 0; mv[2].b = 1;
mv[3].a = 1; mv[3].b = 1;
mv[4].a = 1; mv[4].b = 0;
mv[5].a = 1; mv[5].b = -1;
mv[6].a = 0; mv[6].b = -1;
mv[7].a = -1; mv[7].b = -1;
if(getmap(x1,y1,x2,y2))
cout<<"no"<<endl;
else
cout<<"yes"<<endl;
return 0;
}