题目描述
小明同学沉迷吃鸡,这一天,他又开始了一局刺激的吃鸡游戏,经过一番搜寻,一级套的小明同学准备驱车前往安全区。小明深知地图中一定会埋伏许多LYB,小明希望你能够帮他找到一条到达安全区的安全路线,不要遇到LYB。
输入
第一行为一个整数n,代表地图的大小(n × n);
接下来的n行中,每行包含n个整数a,a=0表示当前位置可以安全通行,a=1表示当前位置有LYB。a=3代表FYX的当前位置,a=4代表安全区。
规定:1 < n <= 100。
输出
输出到达安全路线的最短步数。
示例
输入:5
1 1 0 1 1
3 0 1 1 1
0 0 0 1 1
1 0 1 4 1
0 0 0 0 0
输出:7
BFS
#include<bits/stdc++.h>
using namespace std;
struct node
{
int x;
int y;
int step;
} ;
int a[101][101];
int book[101][101];
int n;
int fl[4][2]={0,1,0,-1,1,0,-1,0};
void bfs(int x,int y)
{
queue<node>q;
node s={x,y,0};
q.push(s);
while(!q.empty())
{
s=q.front();
if(a[s.x][s.y]==4)
{
cout<<s.step<<endl;
return ;
}
for(int i=0;i<=3;i++)
{
int tx=s.x+fl[i][0];
int ty=s.y+fl[i][1];
if(tx>=1&&tx<=n&&ty>=1&&ty<=n&&!book[tx][ty]&&a[tx][ty]!=1)
{
book[tx][ty]=1;
node e1={tx,ty,s.step+1};
q.push(e1);
}
}
q.pop();
}
}
int main()
{
int x,y;
cin>>n;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
cin>>a[i][j];
if(a[i][j]==3)
{
x=i;
y=j;
}
}
book[x][y]=1;
bfs(x,y);
return 0;
}
DFS
#include<stdio.h>
int n,m,p,q,min=99999999,endx,endy;
int a[30][30],book[30][30];
void dfs(int x,int y,int step)
{
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int tx,ty,k;
if(x==endx&&y==endy)
{
if(step<min)
min=step;
return;
}
for(k=0;k<=3;k++)
{
tx=x+next[k][0];
ty=y+next[k][1];
if(tx<1||tx>n||ty<1||ty>n)
continue;
if(a[tx][ty]!=1&&book[tx][ty]==0)
{
book[tx][ty]=1;
dfs(tx,ty,step+1);
book[tx][ty]=0;
}
}
return;
}
int main()
{
int i,j,startx,starty;
scanf("%d",&n);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j]==3)
{
startx=i,starty=j;
}
if(a[i][j]==4)
{
endx=i,endy=j;
}
}
dfs(startx,starty,0);
printf("%d",min);
return 0;
}