• BFS 广搜 最短城市路径


    0为能到达,1为不能一次性到达。

    先使用表格将图转换为树的形式。

    需使用队列的思想(FIFO)。

    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    int city[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,1,0,0,1},
                    {0,0,1,1,0,0,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[1010],b[1010];      //  a[] 经过城市  b[] 前置城市 
    bool s[9]={0};        //标记是否到过这个城市 
    int out(int d)     //输出函数 
    {
        cout<<char(a[d]+64);
        while(b[d]){
            d=b[d];
            cout<<"--"<<char(a[d]+64);
        }
        cout<<endl;
    }
    void bfs()       //BFS
    {
        int head=0,tail=1;
        a[1]=1;
        b[1]=0;
        s[1]=1;
        do{
            head++;
            for(int i=1;i<=8;i++)
            if(city[a[head]][i]==0&&!s[i]){     //判断 是否能到达 
                tail++;
                s[i]=1;
                a[tail]=i;
                b[tail]=head;
                if(i==8){
                    head=tail;
                    out(tail);
                    break;
                }
            }
        }while(head<tail);
    }
    int main()
    {
        bfs();
        return 0;
    }
  • 相关阅读:
    丑数——剑指offer面试题34
    把整数排成最小的数——剑指offer面试题33
    从1到n整数中1出现的次数——剑指offer面试题32
    各种排序方法及其比较
    scrapy安装
    水仙花数
    分数化小数(decimal)
    子序列的和
    倒三角
    韩信点兵
  • 原文地址:https://www.cnblogs.com/sin-mo/p/6154866.html
Copyright © 2020-2023  润新知