判别以邻接表方式存储的有向图中是否存在由顶点vi到顶点vj的路径(i≠j)

试基于图的深度优先搜索策略写一算法,判别以邻接表方式存储的有向图中是否存在由顶点vi到顶点vj的路径(i≠j)。 注意:算法中涉及的图的基本操作必须在此存储结构上实现。

图的邻接表以及相关类型和辅助变量定义如下:

Status visited[MAX_VERTEX_NUM];
typedef char VertexType;
typedef struct ArcNode {
    int adjvex;
    struct ArcNode *nextarc;
} ArcNode;

typedef struct VNode {
    VertexType data;
    ArcNode  *firstarc;
} VNode, AdjList[MAX_VERTEX_NUM];

typedef struct {
    AdjList vertices;
    int vexnum, arcnum;
} ALGraph;
实现函数如下:

Status DfsReachable(ALGraph g, int i, int j)
/* Judge if it exists a path from vertex 'i' to    */
/* vertex 'j' in digraph 'g'.                      */
/* Array 'visited[]' has been initialed to 'false'.*/                       
{
    ArcNode *p;
    Queue Q;
    int e,k;
    InitQueue(Q);
    if(!g.vexnum || !g.arcnum)//图的当前顶点数或弧数为0时
        return ERROR;
    else{
        EnQueue(Q,i);
        while(!QueueEmpty(Q)){
            DeQueue(Q,e);
            visited[e] = TRUE;//标记被访问过的顶点
            p = g.vertices[e].firstarc; 
            for(; p != NULL; p = p -> nextarc){
                k = p -> adjvex;//当前弧所指向顶点的位置
                if(k == j) 
                    return OK;
                else if(!visited[k])//当前顶点未被访问过
                    EnQueue(Q,k);
            }
        }
        return ERROR;
    }
}                                                   


评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值