用两种遍历方法判断图中两点是否有路径(可直接测试)
- 邻接表、图、图的两种遍历以及图中路径的基本概念,可以去自行了解和学习(下面是代码实践)可直接在自己主机测试
#include <iostream>
#include <stdio.h>
#include <stack>
#include <queue>
#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;
}
}
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;
}