题目大意是给出一个二维字符数组,要求在里面寻找一个特定的字母串(大小写均可以),可以是8个方向相邻。
以ABCDE为例子
写的时候思路一不小心就往DFS方向偏移了,还好修正了过来,理清思路后,还是比较容易实现的。模板题,不多说。
#include<iostream>
#include<string.h>
#include<queue>
#define M 100
using namespace std;
char map[M][M];
int dir[8][2] = {{1,1},{1,0},{1,-1},{0,1},{0,-1},{-1,1},{-1,0},{-1,-1}};
char name[5][2] = {{'A','a'},{'B','b'},{'C','c'},{'D','d'},{'E','e'}};
int vis[M][M];
int n,m,sx,sy;
int buff,flag;
struct node{
int x,y,step;
};
int check(int x,int y,int p)
{
// if(map[x][y]==name[p][0]||map[x][y]==name[p][1])
// return 1;
if(x<0||x >= n||y < 0||y >= m)
return 1;
if(vis[x][y])
return 1;
return 0;
}
void bfs()
{
queue<node> q;
node tmp1;
node tmp2;//tmp
tmp1.x = sx;
tmp1.y = sy;
tmp1.step = 0;buff = 0;
q.push(tmp1);
while(!q.empty())
{
tmp1 = q.front();
q.pop();
// cout<<name[tmp1.step][0]<<endl;
if(map[tmp1.x][tmp1.y] == name[tmp1.step][0]||map[tmp1.x][tmp1.y] == name[tmp1.step][1])
buff++;
if(buff==4)
flag = 1;
for(int i = 0 ; i < 8;i++)
{
tmp2 = tmp1;
tmp2.x+=dir[i][0];
tmp2.y+=dir[i][1];
if(check(tmp2.x,tmp2.y,tmp1.step+1))
continue;
tmp2.step =tmp1.step+1;
vis[tmp2.x][tmp2.y] = 1;
q.push(tmp2);
}
}
}
int main()
{
// freopen("str.txt","r",stdin);
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i = 0;i < n;i++)
scanf("%s",&map[i]);
memset(vis,0,sizeof(vis));
flag = 0;
for(int i = 0; i < n;i++)
for(int j = 0;j < m;j++)
if(map[i][j]=='F'||map[i][j]=='f')
{
sx = i;
sy = j;
bfs();
memset(vis,0,sizeof(vis));
}
if(flag)
{
cout<<"yes"<<endl;
}
else if(flag==0)
cout<<"no"<<endl;
}
}