hdu 1728 BFS

来源:互联网 发布:淘宝账号暂时被冻结 编辑:程序博客网 时间:2024/05/22 04:51

这题有一个细节要注意。。。在代码中有提示。。。开始的时候没注意一直WA

AC代码如下:

#include <iostream>#include <queue>#include <cstdio>#include <cstdlib>using namespace std;typedef struct{int x, y;int derect;int num;}Point;int moves[][2] = { -1, 0, 0, 1, 1, 0, 0, -1 };int mark[110][110];int map[110][110];int beginx, beginy, endx, endy, MAX;int N, M;void BFS(){if( map[beginx][beginy] == 0 || map[endx][endy] == 0 ){cout << "no" << endl;return;}Point begin[4];for( int i = 0; i < 4; i++ ){begin[i].x = beginx + moves[i][0];begin[i].y = beginy + moves[i][1];begin[i].derect = i;begin[i].num = 0;}mark[beginx][beginy] = 0;queue<Point> q;for( int i = 0; i < 4; i++ ){if( begin[i].x >= 1 && begin[i].x <= M && begin[i].y >= 1 && begin[i].y <= N && map[begin[i].x][begin[i].y] ){q.push( begin[i] );mark[begin[i].x][begin[i].y] = begin[i].num;}}while( !q.empty() ){Point p;p = q.front();q.pop();for( int i = 0; i < 4; i++ ){Point temp;temp.x = p.x + moves[i][0];temp.y = p.y + moves[i][1];temp.derect = i;if( temp.derect != p.derect ){temp.num = p.num + 1;}else{temp.num = p.num;}if( temp.x < 1 || temp.x > M || temp.y < 1 || temp.y > N || temp.num > MAX || map[temp.x][temp.y] == 0 ){continue;}if( temp.x == endx && temp.y == endy ){cout << "yes" << endl;return;}if( temp.num <= mark[temp.x][temp.y] ){//注意这里有个等于号,因为虽然拐弯数相同,但方向可能不同!!!!mark[temp.x][temp.y] = temp.num;q.push( temp );}}}cout << "no" << endl;}int main(){int t;char c;cin >> t;while( t-- ){cin >> M >> N;getchar();memset( map, 0, sizeof( map ) );for( int i = 1; i <= M; i++ ){for( int j = 1; j <= N; j++ ){c = getchar();if( c == '.'){map[i][j] = 1;}mark[i][j] = 11;}getchar();}cin >> MAX >> beginy >> beginx >> endy >> endx;BFS();}return 0;}