zoukankan      html  css  js  c++  java
  • 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)
    ");
    		return;
    	}
    	printPath(path[u.x][u.y]);
    	printf("(%d, %d)
    ", 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
    ", dis[4][4]);
    	return 0;
    }
    

      

  • 相关阅读:
    Codeforces 722C. Destroying Array
    Codeforces 722D. Generating Sets
    【BZOJ】3436: 小K的农场
    数论四·扩展欧几里德
    数论三·约瑟夫问题
    数论二·Eular质数筛法
    #1287 : 数论一·Miller-Rabin质数测试
    树的维护
    可持久化线段树
    【NOIP2016】天天爱跑步
  • 原文地址:https://www.cnblogs.com/td15980891505/p/5830904.html
Copyright © 2011-2022 走看看