深度优先搜索
#include<cstdio>
#include<iostream>
using namespace std;
#include<cstring>
#include<algorithm>
#include<queue>
#define N 100
int move[4][2]={
0,1,1,0,0,-1,-1,0
};
struct node
{
int x,y,step;
}fa[N][N],road[N*N];
struct node start,next,head;
queue<node>Q;
int n,m,sx,sy,dx,dy;
char a[N][N];
int vis[N][N];
int can[N][N];
void bfs(int x,int y)
{
vis[x][y]=1;
start.x=x;start.y=y;
Q.push(start);
while(!Q.empty())
{
head=Q.front();
Q.pop();
/* printf("-->%d %d",head.x,head.y);
printf("\n");*/
if(head.x==dx&&head.y==dy)return;//找到终点,return
for(int i=0;i<=4;i++)
{
next.x=head.x+move[i][0];
next.y=head.y+move[i][1];
if(next.x<0||next.x>=n||next.y<0||next.y>=m)continue;
if(can[next.x][next.y]&&!vis[next.x][next.y])
{
vis[next.x][next.y]=1;
next.step=head.step+1;
fa[next.x][next.y].x=head.x;//记录路径
fa[next.x][next.y].y=head.y;
Q.push(next);
}
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(vis,0,sizeof(vis));
memset(can,0,sizeof(can));
for(int i=0;i<n;i++)scanf("%s",a[i]);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(a[i][j]=='S'){
sx=i;sy=j;
}
else if(a[i][j]=='D'){
dx=i;dy=j;can[i][j]=1;
}
else if(a[i][j]=='.'){
can[i][j]=1;
}
else if(a[i][j]=='X'){
can[i][j]=0;
}
fa[sx][sy].x=fa[sx][sy].y=-1;
bfs(sx,sy);
printf("%d\n",head.step);//输出最短步数
int k=0,t;
int xx=head.x;
int yy=head.y;
do
{
road[k].x=xx;
road[k++].y=yy;
t=xx;
xx=fa[xx][yy].x;
yy=fa[t][yy].y;
}while(fa[xx][yy].x!=-1);
printf("%d %d\n",sx,sy);
for(int i=k-1;i>=0;i--)printf("%d %d\n",road[i].x,road[i].y);//输出路径
}
}
/*
样例:
4 4
S.X.
..X.
..XD
....
3 4
S.X.
..X.
...D
*/
广度优先搜索
/*#include<queue>
struct node
{
int x,y,step;
bool operator<(const node&that)const{
return step>that.step;
}
}//优先队列
#include<cstdio>
#include<iostream>
using namespace std;
#include<cstring>
#include<algorithm>
#include<queue>
#define N 100
int move[4][2]={
0,1,1,0,0,-1,-1,0
};
char a[N][N];
int step[N][N],can[N][N],vis[N][N];//step记录步数,can记录能否通行,vis记录是否已经走过
int n,m,sx,sy,dx,dy,ans;
void dfs(int x,int y)
{
int tx,ty;
vis[x][y]=1;
if(x==dx&&y==dy)
{
if(step[x][y]<ans)ans=step[x][y];
return;
}
for(int i=0;i<4;i++)
{
tx=x+move[i][0];
ty=y+move[i][1];
if(tx<0||tx>=n||ty<0||ty>=m)continue;
if(!vis[tx][ty]&&can[tx][ty])
{
vis[tx][ty]=1;
step[tx][ty]=step[x][y]+1;
dfs(tx,ty);
step[tx][ty]=step[x][y]-1;
vis[tx][ty]=0;
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(vis,0,sizeof(vis));
memset(step,0,sizeof(step));
ans=100000000;
for(int i=0;i<n;i++)scanf("%s",a[i]);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(a[i][j]=='S'){
sx=i;sy=j;
}
else if(a[i][j]=='D'){
dx=i;dy=j;can[i][j]=1;
}
else if(a[i][j]=='.'){
can[i][j]=1;
}
else if(a[i][j]=='X'){
can[i][j]=0;
}
dfs(sx,sy);
printf("%d\n",ans);
}
}