hdu 1242 Rescue BFS+优先队列
2016-04-06 14:04
253 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242
题意:"r"是起点,"a"是终点,'.'是路,'x'是守卫,'#'是不能走的地方。杀掉守卫要多花1个单位时间,每次上下左右移动要花一个单位时间。问到终点花的最少时间。
思路:这种N*M的地图且带权(一个是1,一个是2)的一般使用BFS+优先队列,如果不带权可以直接使用BFS。
题意:"r"是起点,"a"是终点,'.'是路,'x'是守卫,'#'是不能走的地方。杀掉守卫要多花1个单位时间,每次上下左右移动要花一个单位时间。问到终点花的最少时间。
思路:这种N*M的地图且带权(一个是1,一个是2)的一般使用BFS+优先队列,如果不带权可以直接使用BFS。
#include <bits/stdc++.h> using namespace std; int N, M; #define maxn 210 #define inf 0x3f3f3f3f char mp[maxn][maxn]; int sx, sy, ex, ey; int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; struct Node { int x, y, d; Node(int xx, int yy, int dd) { x = xx; y = yy; d = dd; } Node(){} friend bool operator <(Node a, Node b) { return a.d > b.d; } }; int dist[maxn][maxn]; int bfs() { memset(dist, inf, sizeof(dist)); priority_queue <Node> q; dist[sx][sy] = 0; q.push(Node(sx, sy, 0)); while(!q.empty()) { Node u = q.top(); q.pop(); for(int i = 0; i < 4; i++) { int xx = u.x + dir[i][0]; int yy = u.y + dir[i][1]; //cout<<xx<<" "<<yy<<endl; if(xx < 0 || xx >= N || yy < 0 || yy >= M || mp[xx][yy] == '#') continue; if(mp[xx][yy] == 'a') return u.d+1; Node temp = Node(xx, yy, u.d); temp.d++; if(mp[xx][yy] == 'x') temp.d++; if(dist[xx][yy] >= temp.d) { q.push(temp); dist[xx][yy] = temp.d; } } } return -1; } int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); while(~scanf("%d%d", &N, &M)) { for(int i = 0; i < N; i++) { scanf("%s", mp[i]); } for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { if(mp[i][j] == 'r'){sx = i; sy = j;} if(mp[i][j] == 'a'){ex = i; ey = j;} } } int ans = bfs(); if(ans == -1) printf("Poor ANGEL has to stay in the prison all his life.\n"); else printf("%d\n", ans); } return 0; }
相关文章推荐
- 2016.04.06,英语,《Vocabulary Builder》Unit 10
- 部署zookeeper,zkui,kafka
- leetcode之Range Sum Query - Immutab
- Jenkins上svn: E175002: Processing REPORT request response failed问题的排查过程
- iCheck如何获得id与value
- Android MeasuerSpce using
- (CF#257)B. Jzzhu and Sequences
- Easyui-ComboTree数据填充,递归。树形节点
- 如何为UICollectionView的每一个组设置不同的颜色
- UVA_10099_The Tourist Guide_kruscal
- IPtables中SNAT和MASQUERADE的区别
- Requests库使用
- Android Call requires API level 11 (current min is 8)的解决方案
- Android MeasuerSpec的由来及使用
- NSURL 、NSURLRequest、NSURLConnection、NSURLSession、NSURLSessionDataTask
- UiAutomator viewer 在tools下启动、资源jar包在platforms下(如android22)
- UVa 540 Team Queue
- Java Map 按Key排序和按Value排序
- Ui_Spinner
- iOS监听UITextField的输入事件