2 5 5 ...** *.**. ..... ..... *.... 1 1 1 1 3 5 5 ...** *.**. ..... ..... *.... 2 1 1 1 3
no yes
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
int vis[101][101];
char cnt[101][101];
int t,m,n,k,x1,y1,y2,x2;
int dic[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};
struct A
{
int xx,yy;
int step ;
} ;
void bfs(int x,int y)
{
A cur,next;
queue<A>ls;
vis[x][y]=1;
cur.xx=x;
cur.yy=y;
cur.step=-1;
ls.push(cur);
while(!ls.empty())
{
cur=ls.front();
ls.pop();
if(cur.step>=k) //如果上一次已经搜索完的那一行或列已经等于k的话那么对于 这个结点其他方向的搜索,step肯定更大,直接break完事儿
break;
for(int i=0; i<4; i++) //对于弹出的某个结点,我们深搜到底
{
next.xx=cur.xx+dic[i][0];
next.yy=cur.yy+dic[i][1];
next.step=cur.step+1;
while(1)
{
if(cnt[next.xx][next.yy]!='*'&&next.xx>=0&&next.yy>=0&&next.xx<m&&next.yy<n)//这里不能加是否已经访问过的判断,就因为这里 wa好几个小时
{ //因为要一搜到底如果可以往某个方向走且不出界,就可以继续走,只是不用他已访问过的压入栈、。
if(next.xx==y2-1&&next.yy==x2-1&&next.step<=k)
{
cout<<"yes"<<endl;
return ;
}
if(!vis[next.xx][next.yy])
{
vis[next.xx][next.yy]=1;
ls.push(next);
}
next.xx=next.xx+dic[i][0];
next.yy=next.yy+dic[i][1];
}
else
{
break;
}
}
}
}
cout<<"no"<<endl; // 如果搜索完毕没有按规定找到那么,输出no、
}
int main()
{
cin>>t;
while(t--)
{
cin>>m>>n;
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
cin>>cnt[i][j];
cin>>k>>x1>>y1>>x2>>y2;
if(x1==x2&&y1==y2) //注意两点重合的情况
{
cout<<"yes"<<endl;
continue;
}
memset(vis,0,sizeof(vis));
bfs(y1-1,x1-1);
}
return 0;
}
/****
34
5 6
......
.*.*.*
**.*.*
.*.*.*
......
3 6 1 1 4
2 2
. .
* .
1 1 1 2 2
********/
原文:http://blog.csdn.net/lsgqjh/article/details/45571513