Help the Princess! BFS队列

来源:互联网 发布:阿里云取消手机绑定 编辑:程序博客网 时间:2024/06/14 11:08

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>#include <cmath>using namespace std;const int maxn = 210;const int inff = 1000000;char maze[maxn][maxn];int ans1, ans2;int zou[2][4] = { 0,0,1,-1,1,-1,0,0 };int vis[maxn][maxn];struct node{int x, y, bushu;};void bfs(int x, int y,int h,int w){queue<node> q;node pos, ne;pos.x = x; pos.y = y; pos.bushu = 0;q.push(pos);vis[x][y] = 1;while (!q.empty()){pos = q.front();q.pop();for (int i = 0; i<4; i++){ne.x = pos.x + zou[0][i];ne.y = pos.y + zou[1][i];if (!vis[ne.x][ne.y] && ne.x >= 1 && ne.x <= h && ne.y >= 1 && ne.y <= w && maze[ne.x][ne.y] != '#'){ne.bushu = pos.bushu + 1;vis[ne.x][ne.y] = 1;if (maze[ne.x][ne.y] == '@')ans1 = min(ne.bushu, ans1);else if (maze[ne.x][ne.y] == '$')ans2 = min(ne.bushu, ans2);q.push(ne);}}if (ans1 < inff&& ans2 < inff) break;}}int main(){int h, w, x, y;scanf("%d%d", &h, &w); ans1 = ans2 = inff;getchar();for (int i = 1; i <= h; i++){for (int j = 1; j <= w; j++){scanf("%c", &maze[i][j]);if (maze[i][j] == '%'){x = i; y = j;}}getchar();}bfs(x, y,h,w);if (ans1 < ans2) printf("Yes\n");else printf("No\n");return 0;}

原创粉丝点击