来源:点击打开链接
这个怨念留的实在是太久了,得4-5天了,怎么改都不A,终于在今天AC了。
这个题有好多梗:
1、输入的时候竟然是反着的,先列后行。
2、计算转弯次数就要一口气走到头,而不是半路直接+转弯次数,因为初始的行走方向是不一定的。
3、当起点等于终点的时候要直接返回正确,否则会报错的。
其他的看上去就是很水的BFS了。。
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
char mat[105][105];
int visited[105][105];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int m,n;
int maxturn;
class node
{
public:
int x;
int y;
int turn;
};
node s1,e1;
int judge(int x,int y)
{
if(x>=1 && x<=m && y>=1 && y<=n && mat[x][y]=='.')
return 1;
else
return 0;
}
int bfs(node st,node ed)
{
if(st.x==ed.x && st.y==ed.y) //特殊判断
return 1;
memset(visited,0,sizeof(visited));
queue<node> q;
node first,next;
first.x=st.x;
first.y=st.y;
first.turn=-1;
visited[first.x][first.y]=1;
q.push(first);
while(!q.empty())
{
first=q.front();
q.pop();
for(int i=0;i<4;i++)
{
next.x=first.x+dir[i][0];
next.y=first.y+dir[i][1];
while(judge(next.x,next.y)==1)
{
if(visited[next.x][next.y]==0) //不能因为不能访问就不找了
{
visited[next.x][next.y]=1;
next.turn=first.turn+1;
if(next.x==ed.x && next.y==ed.y && next.turn<=maxturn)
return 1;
q.push(next);
}
next.x+=dir[i][0];
next.y+=dir[i][1];
}
}
}
return 0;
}
int main()
{
int testcase,tx1,ty1,tx2,ty2;
cin>>testcase;
while(testcase--)
{
cin>>m>>n;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
cin>>mat[i][j];
}
}
cin>>maxturn>>tx1>>ty1>>tx2>>ty2;
s1.x=ty1;
s1.y=tx1;
e1.x=ty2;
e1.y=tx2;
if(bfs(s1,e1)==1)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}