深度优先搜索,不难,但费了一番功夫,原因就是因为我的方向写错了(可能也没错 但一直不出结果)
AC代码
#include<stdio.h>
#include<math.h>
char mp[20][20];
char ch[10]="0DSWYBS";//这个地方本来没想到 打错一个一个判断 看到网上这样写 就改了
int sx,sy,ex,ey,flag=0,m,n;
void dfs(int t,int x,int y)
{
int tx,ty;
int dx[8]={0,0,1,-1,1,1,-1,-1};//原来这个地方写的int dir[8][8]={0,1,0,-1,1,0,-1,0,1,1,1,-1,-1,-1,-1,1};
int dy[8]={1,-1,0,0,1,-1,1,-1};//但一直错
if(t==6&&mp[x][y]==ch[t])
{
ex=x,ey=y;
flag=1;//printf("%d %d\n%d %d\n%d",sx,sy,ex,ey,sx+sy+ex+ey);
return;
}
for(int i=0; i<8; i++)
{
tx=x+dx[i];
ty=y+dy[i];
if(tx>=0&&ty>=0&&tx<n&&ty<m&&mp[tx][ty]==ch[t+1])
{
dfs(t+1,tx,ty);
}
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++)
scanf("%s",mp[i]);
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
{
if(mp[i][j]=='D')
{
sx=i;
sy=j;
dfs(1,i,j);
}
if(flag)
{
printf("%d %d\n%d %d\n%d",sx,sy,ex,ey,sx+sy+ex+ey);
return 0;
}
}
printf("DSWYBS\n");
return 0;
}