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;
}

 

posted @ 2016-12-10 09:22  唯莫  阅读(385)  评论(0编辑  收藏  举报