//BFS
/*#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
struct node
{
int x,y,ans;
}q[500];
char ma[16][16];//储存地图
int vis[16][16];//标记访问过的点
int n,m;
int mv[4][2] = {{0,1},{1,0},{-1,0},{0,-1}};//上下左右
void BFS(int x,int y)
{
node f,t;
f.x = x,f.y = y,f.ans = 0;
vis[f.x][f.y] = 1;//当前点访问过
int chu = 0,jin = 0;
q[jin++] = f;
while(chu < jin)
{
t = q[chu++];
if(ma[t.x][t.y]=='Y')
{
printf("%d\n",t.ans);
return ;
}
for(int i = 0;i<4;i++)
{
f.x = t.x + mv[i][0];
f.y = t.y + mv[i][1];
if(0<=f.x&&f.x<n&&0<=f.y&&f.y<m&&!vis[f.x][f.y]&&ma[f.x][f.y]!='#')
{
f.ans = t.ans + 1;
vis[f.x][f.y] = 1;
q[jin++] = f;
}
}
}
puts("-1");
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(vis,0,sizeof(vis));
for(int i = 0;i<n;i++)
scanf("%*c%s",ma[i]);
int i,j;
for(i = 0;i<n;i++)
{
for( j = 0;j<m;j++)
{
if(ma[i][j]=='X')
{
break;
}
}
if(j<m)
break;
}
BFS(i,j);
}
return 0;
}
*/
//DFS
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
const int INF = 1<<20;
using namespace std;
struct node
{
int x,y,ans;
};
char ma[16][16];//储存地图
int vis[16][16];//标记访问过的点
int n,m,mi;
int mv[4][2] = {{0,1},{1,0},{-1,0},{0,-1}};//上下左右
void DFS(int x,int y,int ans)
{
if(ans>=mi)
{
return ;
}
if(ma[x][y]=='Y')
{
if(ans < mi)
{
mi = ans;
}
return ;
}
//printf("%d\n",ans);
node f;
for(int i = 0; i<4; i++)
{
f.x = x + mv[i][0];
f.y = y + mv[i][1];
if(0<=f.x&&f.x<n&&0<=f.y&&f.y<m&&!vis[f.x][f.y]&&ma[f.x][f.y]!='#')
{
vis[f.x][f.y] = 1;
DFS(f.x,f.y,ans + 1);
vis[f.x][f.y] = 0;
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(vis,0,sizeof(vis));
for(int i = 0; i<n; i++)
scanf("%*c%s",ma[i]);
int i,j;
for(i = 0; i<n; i++)
{
for( j = 0; j<m; j++)
{
if(ma[i][j]=='X')
{
break;
}
}
if(j<m)
break;
}
mi = INF;
vis[i][j] = 1;
DFS(i,j,0);
if(mi<INF)
{
printf("%d\n",mi);
}
else
puts("-1");
}
return 0;
}
Download as text
DFS&&BFS模板
最新推荐文章于 2021-12-25 10:20:58 发布