BFS 求无向连通图距离顶点v最远的顶点

本文介绍了一种图的遍历算法——广度优先遍历(BFS),它从图的某个顶点开始,按层次逐步向外扩展,直到遍历完所有可达的顶点。通过邻接表实现图的存储,并提供了广度优先遍历的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

图的广度优先遍历方式是从图的某个顶点开始,由近至远层层拓展的方式遍历图结点的过程,因此图的广度优先遍历的最后一个结点一定是距离该顶点最远的一个结点。

#define MaxSize 10

//邻接表定义
typedef struct ArcNode{
    struct ArcNode* nextArc;
    int arcNum;
}ArcNode;

typedef struct{
    ArcNode* fristArc;
    char data;
}VNode;

typedef struct{
    VNode adjList[MaxSize];
    int n;
    int e;
}AGraph;

void initAGraph(AGraph* &G){
    G->e = 5;
    G->n = 6;
    cout<<"data:"<<endl;
    for (int i = 0; i < G->n; i++) {
        cin>>G->adjList[i].data;
        G->adjList[i].fristArc = NULL;
    }
    cout<<"vi,vj"<<endl;
    for (int j = 0; j < G->e; j++) {
        int vi,vj;
        cin>>vi>>vj;
        ArcNode* node = new ArcNode();
        node->arcNum = vj;
        node->nextArc = G->adjList[vi].fristArc;
        G->adjList[vi].fristArc = node;
    }
}

void ArcVisit(VNode node){
    cout<<"current: "<<node.data<<endl;
}

int visit[MaxSize];

int BFS(AGraph* G,int v){
    //recursion terminator
    if (G == NULL) {
        return -1;
    }
    int queue[MaxSize];
    int front = 0;
    int rear = 0;
    int num = v;
    
    //root gets into queue;
    rear = (rear + 1)%MaxSize;
    queue[rear] = num;
    ArcVisit(G->adjList[num]);
    visit[num] = 1;
    ArcNode* node;
    
    //process logic
    while(front != rear) {
        front = (front + 1)%MaxSize;
        num = queue[front];
        node = G->adjList[num].fristArc;
        while (node) {
            if (visit[node->arcNum] == 0) {
                ArcVisit(G->adjList[node->arcNum]);
                visit[node->arcNum] = 1;
                rear = (rear+1)%MaxSize;
                queue[rear] = node->arcNum;
            }
            node = node->nextArc;
        }
    }
    return num;
}

int main(int argc, const char * argv[]) {
    AGraph* G = new AGraph();
    initAGraph(G);
    cout<<"Last:"<< BFS(G, 0)<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值