点击打开链接
起初看了这个题没什么思路,后来偶然在其他oj上做了一道类似的也就明白了。
主要就是在一个点按照一个方向一直搜下去,直到不能搜。
这样再搜就会转弯了。
不多说,贴出代码
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#define max 101
using namespace std;
int go[4][2] = {{-1,0},{0,-1},{0,1},{1,0}};
char a[max][max];
int vis[max][max];
int t,n,m,k;
int sx,sy,ex,ey;
struct node
{
int x,y,step;
}s,e;
void bfs(int x1,int y1)
{
memset(vis,0,sizeof(vis));
s.x = x1, s.y = y1, s.step = -1;
vis[x1][y1] = 1;
queue<node>q;
q.push(s);
while(!q.empty())
{
s = q.front();
if(s.step>=k)
{
cout << "NO" << endl;
return;
}
q.pop();
for(int i = 0; i < 4; i++)
{
e.x = s.x + go[i][0];
e.y = s.y + go[i][1];
e.step = s.step + 1;
while(1)
{
if(e.x>=0&&e.x<n&&e.y>=0&&e.y<m&&a[e.x][e.y]=='.')
{
if(e.x == ex&&e.y == ey)
{
cout << "YES" <<endl;
return ;
}
if(vis[e.x][e.y]==0)
{
vis[e.x][e.y] = 1;
q.push(e);
}
e.x+=go[i][0];
e.y+=go[i][1];
}
else
break;
}
}
}
cout << "NO" << endl;
}
int main()
{
cin >> t;
while(t--)
{
cin >> n >> m >> k;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
cin >> a[i][j];
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{
if(a[i][j] == 'S')
{
sx = i,sy = j;
}
if(a[i][j] == 'P')
{
ex = i,ey = j;
a[ex][ey] = '.';
}
}
bfs(sx,sy);
}
return 0;
}