zoukankan      html  css  js  c++  java
  • BFS_最短路径

    已知若干个城市的地图,求从一个城市到另一个城市的路径,要求路径中经过的城市最少。

    #include<iostream>
    #include<cstring>
    using namespace std;
    int ju[9][9]=
    {{0,0,0,0,0,0,0,0,0},
    {0,1,0,0,0,1,0,1,1},
    {0,0,1,1,1,0,1,1,1},
    {0,0,1,0,0,1,1,1,1},
    {0,0,1,0,1,1,1,0,1},
    {0,1,1,0,1,1,1,0,0},
    {0,0,0,1,1,1,1,1,0},
    {0,1,1,1,0,0,1,1,0},
    {0,1,1,1,1,0,0,0,1}};
    int a[101],b[101],s[9],head,tail;
    void print(int d)
    {
        cout << char(a[d]+64);
        while(b[d]){
            d=b[d];
            cout << "--" << char(a[d]+64);
        }
        cout << endl;
    }
    void bfs()
    {
        int i;
        head=0;tail=1;         //tail依次记录每个节点 
        a[1]=1;b[1]=0;s[1]=1;  //a数组记录每个节点上城市,b数组记录上一个城市的节点,s记录走过的城市 
        do{
            head++;
            for(i=1;i<=8;i++){
                if(ju[a[head]][i]==0 && s[i]==0){
                    tail++;
                    a[tail]=i;
                    b[tail]=head;
                    s[i]=1;
                    if(i==8) {
                        print(tail);
                        return;
                    }
                }
            }
        }while(head<tail);
    }
    int main()
    {
        memset(s,0,sizeof(s));
        bfs();
        return 0;
    }
    View Code
  • 相关阅读:
    DC中为什么要用Uniquify?
    hdu 1596 find the safest road
    hdu2112 HDU Today
    hdu 2066 一个人的旅行
    poj 3026 Borg Maze
    poj 1979 Red and Black
    poj 1321 棋盘问题
    hdu 1010 Tempter of the Bone
    hdu 4861 Couple doubi
    codeforces584B Kolya and Tanya
  • 原文地址:https://www.cnblogs.com/a867686201/p/6154947.html
Copyright © 2011-2022 走看看