BFS 判断顶点i和顶点j是否有路径

从顶点i开始到顶点j进行一次BFS,遍历过程如果访问到了vj,则判定vi与vj存在路径。


#define MaxSize 10

typedef struct ArcNode{
    struct ArcNode* next;
    int adjNum;
}ArcNode;

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

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

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

int visit[MaxSize];

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

//Judge the path of vi to vj is valid
int ValidPath(AGraph* G,int vi, int vj){
    int queue[MaxSize];
    int front = 0,rear = 0;
    ArcNode* node;
    
    //Root gets into queue
    rear = (rear + 1)%MaxSize;
    queue[rear] = vi;
    ArcVisit(G->adjList[vi]);

    //Process current logic
    while (front != rear) {
        front = (front + 1)%MaxSize;
        int num = queue[front];
        node = G->adjList[num].firstArc;
        while (node) {
            rear = (rear + 1)%MaxSize;
            queue[rear] = node->adjNum;
            if (visit[node->adjNum] == 0) {
                ArcVisit(G->adjList[node->adjNum]);
                visit[node->adjNum] = 1;
            }
            node = node->next;
        }
    }
    if (visit[vj] == 1) {
        return 1;
    }else{
        return 0;
    }
}


int main(int argc, const char * argv[]) {
    AGraph* G = new AGraph();
    initAGraph(G);
    int ret = ValidPath(G, 0, 3);
    cout<<"valid:"<<ret<<endl;
    return 0;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值