POJ 3170 Knights of Ni (暴力,双向BFS)
2016-07-28 21:13
274 查看
题意:一个人要从2先走到4再走到3,计算最少路径。
析:其实这个题很水的,就是要注意,在没有到4之前是不能经过3的,一点要注意。其他的就比较简单了,就是一个双向BFS,先从2搜到4,再从3到搜到4,
然后求最短路即可。
代码如下:
析:其实这个题很水的,就是要注意,在没有到4之前是不能经过3的,一点要注意。其他的就比较简单了,就是一个双向BFS,先从2搜到4,再从3到搜到4,
然后求最短路即可。
代码如下:
#include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <string> #include <algorithm> #include <vector> #include <map> using namespace std ; typedef long long LL; typedef pair<int, int> P; template<class T>T scan(T &x){ int f = 1; x = 0; char c; while(c = getchar(), c < 48) if(c == '-') f = -1; do x = x * 10 + (c^48); while(c = getchar(), c > 47); x *= f; return x; } const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f3f; const double eps = 1e-11; const int maxn = 1000 + 5; const int dr[] = {0, 0, -1, 1}; const int dc[] = {-1, 1, 0, 0}; struct node{ int x, y; node(int xx = 0, int yy = 0) : x(xx), y(yy) { } }; int n, m; int a[maxn][maxn]; int vis1[maxn][maxn]; int vis2[maxn][maxn]; vector<node> v; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } void bfs(int r, int c, int vis[][maxn], bool ok){ queue<node> q; q.push(node(r, c)); vis[r][c] = 0; while(!q.empty()){ node u = q.front(); q.pop(); for(int i = 0; i < 4; ++i){ int x = u.x + dr[i]; int y = u.y + dc[i]; if(vis[x][y] != INF || !is_in(x, y) || a[x][y] == 1) continue; if(!ok && a[x][y] == 3) continue; vis[x][y] = vis[u.x][u.y] + 1; q.push(node(x, y)); } } } int main(){ scanf("%d %d", &m, &n); int sx, sy, ex, ey; for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j){ scanf("%d", &a[i][j]); if(a[i][j] == 4) v.push_back(node(i, j)); else if(a[i][j] == 2) sx = i, sy = j; else if(a[i][j] == 3) ex = i, ey = j; } for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j) vis1[i][j] = vis2[i][j] = INF; bfs(sx, sy, vis1, false); bfs(ex, ey, vis2, true); int ans = INF; for(int i = 0; i < v.size(); ++i){ ans = min(ans, vis1[v[i].x][v[i].y]+vis2[v[i].x][v[i].y]); } cout << ans << endl; return 0; }
相关文章推荐
- SQL Server 常用的数据类型
- 掌握zigbee网络里的相关的重要概论
- List remove注意点
- HDOJ-1241 Oil Deposits
- 关于火狐和IE下select控制div
- bat面试内容
- mysql命令2
- jQuery 绑定 select 联动 手动触发
- Android 耳机按键与拔插监听
- iOS开发网络篇—监测网络状态
- 数据库数据拷贝
- ViewPager、ViewPager和Fragment组合使用的基本用法
- Codeforces 103A Testing Pants for Sadness
- kubernetes 1.3 的安装和集群环境部署
- MySQL之逻辑查询处理流程
- 简单的自我介绍
- not,and,or
- pip卡住不动的解决方案
- java 内存模型(JMM)简介
- 主从复制读写分离多种方案