从顶点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;
}