dfs模版
dfs
#include <stdio.h>
#include <string.h>
char Map[16][16];
int mv[16][16];
//mv[i][j] == 0 没有被访问
//mv[i][j] == 1 已经被访问
struct N
{
int x,y;
} ;
int jx[] = { 0,-1, 0, 1};
int jy[] = { 1, 0,-1, 0};
int Min;
void dfs(int x,int y,int n,int m,int ans)
{
if(ans >= Min)
{
return ;
}
if(Map[x][y] == 'Y')
{
if(ans < Min)
{
Min = ans;
}
return ;
}
N f;
for(int i = 0; i < 4; ++i)
{
f.x = x + jx[i];
f.y = y + jy[i];
if(0 <= f.x && f.x < n && 0 <= f.y && f.y < m && mv[f.x][f.y] == 0 && Map[f.x][f.y] != '#')
{
mv[f.x][f.y] = 1;
dfs(f.x,f.y,n,m,ans+1);
mv[f.x][f.y] = 0;
}
}
}
int main()
{
int n,m,i,j;
while(scanf("%d %d",&n,&m) != EOF)
{
memset(mv,0,sizeof(mv));
for(i = 0; i < n; ++i)
{
scanf("%*c%s",Map[i]);
}
for(i = 0; i < n; ++i)
{
for(j = 0; j < m; ++j)
{
if(Map[i][j] == 'X')
break;
}
if(j != m)
break;
}
Min = (1<<20);
dfs(i,j,n,m,0);
if(Min == (1<<20))
{
printf("-1\n");
}
else
{
printf("%d\n",Min);
}
}
return 0;
}