BFS求最短路


   假設有一個n行m列的迷宮,每個單位要么是空地(用1表示)要么是障礙物(用0表示).如和找到從起點到終點的最短路徑?利用BFS搜索,逐步計算出每個節點到起點的最短距離,以及最短路徑每個節點的前一個節點。最終將生成一顆以起點為根的BFS樹。此時BFS可以求出任意一點到起點的距離。

/*poj3984
---BFS求最短路
--*/
#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 5;

struct Node{
	int x, y;
	Node(int a=0, int b=0) :x(a), y(b){}
};
int G[maxn][maxn];
int dis[maxn][maxn];
Node path[maxn][maxn];

const int dir[4][2] = { { 0, 1 }, { 0, -1 }, { -1, 0 }, { 1, 0 } };
bool isleg(int x, int y){
	return (x>=0&& y >= 0 && x < maxn&&y < maxn
		&&dis[x][y] == -1&&!G[x][y]);
}
void bfs(){
	queue<Node>Q;
	Q.push(Node(0, 0));
	memset(dis, -1, sizeof(dis));
	dis[0][0] = 0;
	while (!Q.empty()){
		Node u = Q.front(); Q.pop();
		for (int i = 0; i < 4; i++){
			int dx = u.x +dir[i][0];
			int dy = u.y + dir[i][1];
			if (isleg(dx, dy)){
				dis[dx][dy] = dis[u.x][u.y] + 1;
				path[dx][dy] = u;
				Q.push(Node(dx, dy));
			}
		}
	}
}
void printPath(Node u){
	if (!u.x&&!u.y){
		printf("(0, 0)\n");
		return;
	}
	printPath(path[u.x][u.y]);
	printf("(%d, %d)\n", u.x, u.y);
}
int main(){
	int i, j;
	for (i = 0; i < maxn;i++)
	for (j = 0; j < maxn; j++)
		scanf("%d", &G[i][j]);
	bfs();
	printPath(Node(4, 4));//printf("%d\n", dis[4][4]);
	return 0;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM