hdu 2822 bfs
2015-10-06 09:56
302 查看
问题可以抽象为求起点到终点的最短路,其中经过x的代价是0,而经过.的代价是1,bfs的时候用优先队列即可。
#include <iostream> #include <cstring> #include <cstdio> #include <queue> using namespace std; const int N = 1001; char maze ; bool visit ; int dx[] = { 0, 0, 1, -1 }; int dy[] = { 1, -1, 0, 0 }; int n, m, sx, sy, ex, ey; bool ok( int x, int y ) { return x >= 0 && x < n && y >= 0 && y < m && !visit[x][y]; } struct Node { int x, y, t; Node(){} Node( int _x, int _y, int _t ) { x = _x, y = _y, t = _t; } bool operator < ( const Node & o ) const { return t > o.t; } }; priority_queue<Node> q; int bfs() { while ( !q.empty() ) q.pop(); memset( visit, 0, sizeof(visit) ); q.push( Node( sx, sy, 0 ) ); visit[sx][sy] = 1; while ( !q.empty() ) { Node cur = q.top(); q.pop(); if ( cur.x == ex && cur.y == ey ) return cur.t; for ( int i = 0; i < 4; i++ ) { int x = cur.x + dx[i]; int y = cur.y + dy[i]; if ( ok( x, y ) ) { int d = maze[x][y] == '.' ? 1 : 0; q.push( Node( x, y, cur.t + d ) ); visit[x][y] = 1; } } } return -1; } int main () { while ( scanf("%d%d", &n, &m) != EOF ) { if ( !n && !m ) break; for ( int i = 0; i < n; i++ ) { scanf("%s", maze[i]); } scanf("%d%d%d%d", &sx, &sy, &ex, &ey); sx--, sy--, ex--, ey--; int ans = bfs(); printf("%d\n", ans); } return 0; }
相关文章推荐
- MeteoInfoLab脚本示例:合并数组
- 【mongoDB高级篇①】聚集运算之group,aggregate
- 应用层HTTP,FTP,TFTP,TELNET,DNS,EMAIL
- QT5 学习之路28---坐标系统
- DLX重复覆盖 fzu1686 神龙的难题
- java代码 分解EXCEL(一)
- 今天进行2005sql server数据库还原操作时,提示备份中数据库与现有数据库不同
- gzip头部格式
- iOS开发 —— Objective C语言知识点总结
- strstr_while模型
- 弹出层控件popup
- win7+ubuntu 13.04双系统安装方法
- iOS 发送Email
- 传统轮播
- Using DAVID for GO and pathway enrichment analysi
- 线性表的链式实现
- VIjosP1046观光旅游
- DLX精确覆盖 zoj3209 Treasure Map
- 【Linux高频命令专题(13)】cat
- 集合视图源码解析