POJ 3170 Knights of Ni (暴力,双向BFS)

题意:一个人要从2先走到4再走到3,计算最少路径。

析:其实这个题很水的,就是要注意,在没有到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;
}
上一篇:Win32 GDI 在内存中绘制彩色的位图


下一篇:html5增强的页面元素