/**
* 王道书 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;
}
王道书 P217 T04
最新推荐文章于 2023-09-02 20:55:32 发布