用两种遍历方法判断图中两点是否有路径

用两种遍历方法判断图中两点是否有路径(可直接测试)

  • 邻接表、图、图的两种遍历以及图中路径的基本概念,可以去自行了解和学习(下面是代码实践)可直接在自己主机测试
#include 
#include 
#include 
#include 
#define null NULL
#define max_n 101

using namespace std;

typedef int vexType;
int visited[max_n];
//邻接表
typedef struct arcnode{
    vexType vexid;
    struct arcnode *nextarc;
}ArcNode,Vnode,vexList[max_n];

typedef struct {
    int vexnum,edgenum;
    vexList vexs;
}ALGraph;
//遍历标记数组
void clear_visited(){
    fill(visited,visited+max_n,false);
}
//图的初始化与展示函数
void init_g(ALGraph &g){
    for(int i=0;i<=g.vexnum;i++){
        g.vexs[i].vexid=i;
        g.vexs[i].nextarc=null;
    }

}
void show_g(ALGraph g){
    for(int i=1;i<=g.vexnum;i++){
        cout<<g.vexs[i].vexid<<"->";
        ArcNode *p=g.vexs[i].nextarc;
        while(p){
            cout<<p->vexid<<"-";
            p=p->nextarc;
        }
        cout<<"^"<<endl;
    }
}
/*
 * 测试样例
 4 5 3 4
 1 2
 1 3
 2 3
 2 4
 3 4
 */
/*
 5 5 1 5
 1 2
 1 3
 2 3
 2 4
 3 4
 */
//两种遍历方式判断两点间是否有路径
bool Is_HasPath_BFS(ALGraph g,int i,int j);
bool Is_HasPath_DFS(ALGraph g,int i,int j);
bool dfs(ALGraph g,int v,int j);
bool bfs(ALGraph g,int v,int j);

int main() {
    ALGraph graph;
    int m,n,u,v,ii,jj;
    cin>>n>>m>>ii>>jj;
    graph.vexnum=n;
    graph.edgenum=m;
    //初始
    init_g(graph);
    //建立图(无向邻接表)
    for(int i=0;i<m;i++){
        cin>>u>>v;
        ArcNode *p=(ArcNode *)malloc(sizeof(ArcNode));
        ArcNode *q=(ArcNode *)malloc(sizeof(ArcNode));
        p->vexid=u; p->nextarc=null;
        q->vexid=v; q->nextarc=null;
        p->nextarc=graph.vexs[v].nextarc;
        graph.vexs[v].nextarc=p;
        q->nextarc=graph.vexs[u].nextarc;
        graph.vexs[u].nextarc=q;
    }
    show_g(graph);
    //判断
    if(Is_HasPath_DFS(graph,ii,jj)) printf("Yes\n");
    else printf("No\n");
    if(Is_HasPath_BFS(graph,ii,jj)) printf("Yes");
    else printf("No");
    return 0;
}

bool dfs(ALGraph g,int v,int j){
    static bool flag=false;//一次保存周期使用
    if(v==j) flag=true;
    visited[v]=true;
    ArcNode *p=g.vexs[v].nextarc;
    while(p){
        if(!visited[p->vexid]){
            dfs(g,p->vexid,j);
        }
        p=p->nextarc;
    }
    return flag;
}
bool Is_HasPath_DFS(ALGraph g,int i,int j){
    clear_visited();
    return dfs(g,i,j);
}
bool Is_HasPath_BFS(ALGraph g,int i,int j){
    clear_visited();
    return bfs(g,i,j);
}
bool bfs(ALGraph g,int v,int j){
    if(v==j) return true;//用队列保存和处理层次路径
    visited[v]=true;
    queue<int> pq;
    pq.push(v);
    while(!pq.empty()){
        int id=pq.front();
        pq.pop();
        ArcNode *p=g.vexs[id].nextarc;
        while (p){
            if(!visited[p->vexid]){
                if(p->vexid==j) return true;
                visited[p->vexid]=true;
                pq.push(p->vexid);
            }
            p=p->nextarc;
        }
    }
    return false;
}

你可能感兴趣的:(算法学习与进阶,指针,题目练习与进阶,图论,算法,c语言,c++)