您的位置:首页 > 其它

RQNOJ 195校园迷宫(简单BFS)

2012-05-14 12:40 281 查看
/*
*  简单BFS
*/

#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int N = 2005;

int map

;
bool vis

;
struct node {
int x;
int y;
int c;
}Q[N*N], s, e;
int front, rear;
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

int BFS(int n, int m) {
node first, next;
memset(vis, true, sizeof(vis));
front = rear = 0;
vis[s.x][s.y] = false;
Q[front++] = s;
while (rear < front) {
first = Q[rear++];
if (first.x==e.x && first.y==e.y) return first.c;
for (int i=0; i<4; ++i) {
next.x = first.x + dir[i][0];
next.y = first.y + dir[i][1];
next.c = first.c + 1;
if (next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&vis[next.x][next.y]&&map[next.x][next.y]==0) {
Q[front++] = next;
vis[next.x][next.y] = false;
}
}
}
return -1;
}

int main() {
int n, m;
while (scanf("%d%d", &n, &m) != EOF) {
for (int i=0; i<n; ++i) {
for (int j=0; j<m; ++j) scanf ("%d", &map[i][j]);
}
scanf ("%d%d%d%d", &s.x, &s.y, &e.x, &e.y);
--s.x, --s.y, --e.x, --e.y;
s.c = 0;
int ans = BFS(n, m);
if (ans < 0) printf ("No Answer!\n");
else printf ("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: