1180 bfs

来源:互联网 发布:php loop循环 编辑:程序博客网 时间:2024/05/04 13:37

一道典型的 bfs。这个题的“天梯”有点坑。在判断,讨论天梯的方向的时候有点麻烦

跪了两次:

1. 在经过天梯后,依然需要check一次。。。

2. 原地不动的时候,我居然直接把now修改了,跪了一次。。。


#pragma warning(disable:4996)#include <iostream>#include <stdio.h>#include <algorithm>#include <string>#include <cstring>#include <vector>#include <queue>using namespace std;int m, n;int sx, sy;char mapp[25][25];int vis[25][25];int mx[4] = { -1, 0, 1, 0 };int my[4] = { 0, 1, 0, -1 };int ans;struct Node{int x, y;int time;Node(int a, int b, int c){x = a; y = b; time = c;}friend bool operator<(const Node &a, const Node &b){return a.time>b.time;}};bool check(Node & a){int x = a.x;int y = a.y;if (x<1 || x>m || y<1 || y>n || mapp[x][y] == '*' || vis[x][y] == 1)return 0;return 1;}void bfs(){Node now(sx, sy, 0);vis[sx][sy] = 1;priority_queue<Node> q;q.push(now);while (!q.empty()){now = q.top();q.pop();if (mapp[now.x][now.y] == 'T'){ans = now.time;return;}for (int i = 0; i < 4; ++i){Node next(now.x + mx[i], now.y + my[i], now.time + 1);if (check(next)){if (mapp[next.x][next.y] == '.' || mapp[next.x][next.y] == 'T'){q.push(next);vis[next.x][next.y] = 1;}else if (mapp[next.x][next.y] == '|'){if (next.time % 2 == 0 && i % 2 == 1)  //横向移动{next.y += my[i];if (check(next)){q.push(next);vis[next.x][next.y] = 1;}}else if (next.time % 2 == 1 && i % 2 == 0)  //竖向移动{next.x += mx[i];if (check(next)){q.push(next);vis[next.x][next.y] = 1;}}else   //原地不动{Node next2(now.x, now.y, now.time + 1);q.push(next2);}}else if (mapp[next.x][next.y] == '-'){if (next.time % 2 == 1 && i % 2 == 1)  //横向移动{next.y += my[i];if (check(next)){q.push(next);vis[next.x][next.y] = 1;}}else if (next.time % 2 == 0 && i % 2 == 0)  //竖向移动{next.x += mx[i];if (check(next)){q.push(next);vis[next.x][next.y] = 1;}}else    //原地不动{Node next2(now.x, now.y, now.time + 1);q.push(next2);}}}}}}int main(){freopen("in.txt", "r", stdin);while (cin >> m >> n){memset(vis, 0, sizeof(vis));for (int i = 1; i <= m; ++i){for (int j = 1; j <= n; ++j){cin >> mapp[i][j];if (mapp[i][j] == 'S'){sx = i; sy = j;}}}bfs();cout << ans << endl;}return 0;}

0 0
原创粉丝点击