RQNOJ 34紧急救援(简单BFS)

#include <cstdio>

#include <cstring>

#include <iostream>



using namespace std;



const int N = 1005;



char map[N][N], vis[N][N];

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) {

	node first, next;

	front = rear = 0;

	Q[front++] = s;

	memset(vis, true, sizeof(vis));

	vis[s.x][s.y] = false;

	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<n&&vis[next.x][next.y]&&map[next.x][next.y]=='0') {

				Q[front++] = next;

				vis[next.x][next.y] = false;

			}

		}

	}

}



int main() {

	int n;

	while (scanf("%d", &n) != EOF) {

		for (int i=0; i<n; ++i) scanf("%s", map[i]);

		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 dis = BFS(n);

		printf ("%d\n", dis);

	}

	return 0;

}

  

你可能感兴趣的:(bfs)