nyoj--284 坦克大战(bfs+优先队列)
2016-03-19 12:36
471 查看
nyoj 284
因此使用优先队列,每一次走都选择步数最少的进行扩展。
题解
与一般的迷宫问题不同,这里的每一点如果可扩展,可能要走1步或者2步,如果用普通的队列,无法保证到达终点时步数最少。因此使用优先队列,每一次走都选择步数最少的进行扩展。
#include <iostream> #include <queue> #include <cstring> #include <string> #include <cstdio> #include <algorithm> using namespace std; const int maxn = 300 + 10; const int inf = 1 << 30; char maze[maxn][maxn]; int dir[4][2] = { {-1, 0}, {1, 0}, {0, 1}, {0, -1} }; int sx, sy, ex, ey; int m, n; struct node{ int x, y; int turn; bool operator < (const node& rhs) const { return turn > rhs.turn; } }; int bfs() { priority_queue<node> Q; Q.push(node{sx, sy, 0}); while(!Q.empty()) { node u = Q.top(); Q.pop(); if(u.x == ex && u.y == ey) return u.turn; for(int i = 0; i < 4; ++i) { int nx = u.x + dir[i][0], ny = u.y + dir[i][1]; if(nx < 0 || nx >= m || ny < 0 || ny >= n || maze[nx][ny] == 'S' || maze[nx][ny] == 'R') continue; if(maze[nx][ny] == 'B') Q.push(node{nx, ny, u.turn + 2}); else Q.push(node{nx, ny, u.turn + 1}); maze[nx][ny] = 'S'; //访问过的不再访问,防止扩展 } } return -1; } int main() { while(cin >> m >> n && (m || n)) { for(int i = 0; i < m; ++i) { for(int j = 0; j < n; ++j) { cin >> maze[i][j]; if(maze[i][j] == 'Y') sx = i, sy = j; if(maze[i][j] == 'T') ex = i, ey = j; } } cout << bfs() << endl; } return 0; }
相关文章推荐
- Surrounded Regions
- Word Ladder, Gray Code
- UVA 11624
- HDU1495
- HDU2612 Find a way
- HDU1241 Oil Deposits
- Hdu2444二分图
- 最少步数BFS
- 转v_JULY_v的 BFS和DFS优先搜索算法
- 2015 寒假搜索专题 I - Meteor Shower(BFS)
- Same Tree
- E - Roads in the North
- DFS&BFS算法总结(1)
- Word Ladder I
- 图的BFS和DFS学习笔记
- [LeetCode] Binary Tree Level Order Traversal
- [LeetCode] Binary Tree Level Order Traversal II
- 关于BFS搜索的思想, 最简单的水题,不过深有体会啊。
- Word Ladder II
- Surrounded Regions