题目:http://acm.hdu.edu.cn/showproblem.php?pid=1728
单方向的bfs
要用队头来遍历完所有最优解并且进队,再重复
如果每次让周围四个节点入队,此时在同行、同列还有最优解没进队,导致那些之前没进队的,进队的时候就已经不是最优解了。
#include <cstdio>
#include <queue>
#include <cstring>
using std::queue;
struct node
{
int x,y,turn;
};
int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
char map[105][105];
int book[105][105];
node nstart,nend;
int main()
{
int T,m,n,i,j;
scanf("%d",&T);
while(T--)
{
memset(book, 0, sizeof(book));
scanf("%d %d",&m,&n);
for(i = 1; i <= m; ++i)
for(j = 1; j <= n; ++j)
scanf(" %c",&map[i][j]);
int di;
scanf("%d %d %d %d %d",&di,&nstart.y,&nstart.x,&nend.y,&nend.x);
book[nstart.x][nstart.y] = 1;
if(nstart.x == nend.x && nstart.y == nend.y)
{
printf("yes\n");
continue;
}
nstart.turn = -1;
queue<node> que;
que.push(nstart);
node cur,pre;
int flag = 0;
while(!que.empty())
{
pre = que.front();
que.pop();
if(pre.x == nend.x && pre.y == nend.y && pre.turn <= di)
{
printf("yes\n");
flag = 1;
break;
}
cur.turn = pre.turn + 1;
for(int k = 0; k < 4; ++k)
{
cur.x = pre.x + next[k][0];
cur.y = pre.y + next[k][1];
while(cur.x > 0 && cur.y > 0 && cur.x <= m && cur.y <= n && cur.turn <= di && map[cur.x][cur.y] == '.')
{
if(!book[cur.x][cur.y])
{
que.push(cur);
book[cur.x][cur.y] = 1;
}
cur.x += next[k][0];
cur.y += next[k][1];
}
}
}
if(!flag)
printf("no\n");
}
return 0;
}