王道书 P217 T04

/**
 * 王道书 P217 T04
 *
 * ①算法思想
 * 如果 Vi 到 Vk有路径,Vk 到 Vj有路径,那么 Vi 到 Vj有路径。
 * 广度:从 Vi 开始往外探索,如果有一个点是 Vj,就说明 Vi 和 Vj 之间有路径。
 * 深度:从 Vi 开始往深处探索,如果有一个点是 Vj,就说明 Vi 和 Vj 之间有路径。
 *
 * ②算法设计
 *
 */

#include <stdio.h>
#include <iostream>
#include <cstdio>
#include <malloc.h>
#include <cstdlib>
#define MaxSize 20
#define INF 999999

//王道书 P217 T04
//①广度:把BFS拿来修改
struct ArcNode{
    int adjvex;//顶点下标
    struct ArcNode *next;
    int weight;
};
struct VNode{
    char value;
    struct ArcNode *first;
};
struct AdGraph{
    VNode vertices[MaxSize];
    int vexnum,arcnum;
};
bool BFS(AdGraph G,int i,int j){//v是起点顶点的数组下标
    int visited[MaxSize];
    int Queue[MaxSize],front = -1,rear = -1;//队列,保存入入队的点的序号
    //第一个起点一定没被遍历,直接入队
    Queue[++rear] = i;//这是第一个起点v
    visited[i] = 1;
    //接下来进行逻辑
    while(front != rear){//直到队空,说明此轮trap遍历结束
        i = Queue[++front];//出队对头顶点,判断出队顶点周围顶点是否有没有没被遍历的
        //拿到顶点v的边链表
        ArcNode *p = G.vertices[i].first;//这边是每次的出队v
        while(p){
            if(!visited[p -> adjvex]){
                if(p -> adjvex == j)
                    return true;
                visited[p -> adjvex] = 1;
                Queue[++rear] = p -> adjvex;//没被访问过的这个顶点的下标入队
            }
            p = p -> next;
        }
    }
    return false;//如果没有因为true出去的话,就要return false;
}
//②深度:不太好把DFS拿来修改,要重新写一下
struct ArcNode{
    int adjvex;
    struct ArcNode *next;
    int weight;
};
struct VNode{
    char value;
    struct ArcNode *first;
};
struct AdGraph{
    VNode vertices[MaxSize];
    int vexnum,arcnum;
};
void DFSPath(AdGraph G,int i,int j,int &isPath,int *visited){
    if(i == j)
        isPath = 1;
    visited[i] = 1;
    ArcNode *p = G.vertices[i].first;
    while(p){//递归
        if(!visited[p -> adjvex])
            DFSPath(G,p -> adjvex,j,isPath,visited);
        p = p -> next;
    }
}
bool IsPathDFS(AdGraph G,int i,int j){
    int visited[MaxSize];
    for (int i = 0; i < G.vexnum; ++i) {
        visited[i] = 0;
    }
    int isPath = 0;//默认是没有的
    DFSPath(G,i,j,isPath,visited);
    return isPath == 1;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值