图的遍历算法 有两种 :深度优先搜索遍历 和 广度 优先搜索遍历。深度优先搜索遍历类似与 树的 先序遍历。广度优先搜索遍历类似与树的层序遍历。只不过 图 可以有 不连通的 节点,所以 得 遍历 整个顶点数组。
深搜遍历 总是 先访问当前节点的邻接点,而 广搜算法 是 先访问顶点的邻接点 要 先于 后访问顶点的邻接点 被 访问。
具体遍历顺序如下:
以下代码 以 图的 邻接多重表 为 基本结构进行 遍历。
首先更改 上节 的 查找 邻接点 和 下一个邻接点的 返回值,以及 邻接点的 代码 有误,少加了 一句:
if (next->iIndex == location2 || next->jIndex == location2){
next = next->iIndex == location1 ? next->iNext : next->jNext;
break;
}
next = next->iIndex == location1 ? next->iNext : next->jNext;
int firstAdj(AMLGraph g,int location){
ArcNode * next = g.adjMuList[location].head->iNext;
if (next != NULL)
{
int index = next->iIndex == location ? next->jIndex : next->iIndex;
return index;
}
return -1;
}
int nextAdj(AMLGraph g,int location1 ,int location2){
ArcNode * next = g.adjMuList[location1].head->iNext;
while (next != NULL){
if (next->iIndex == location2 || next->jIndex == location2){
next = next->iIndex == location1 ? next->iNext : next->jNext;
break;
}
next = next->iIndex == location1 ? next->iNext : next->jNext;
}
if (next != NULL){
int index = next->iIndex == location1 ? next->jIndex : next->iIndex;
return index;
}
return -1;
}
void dfs(AMLGraph g,int i,bool * isVisitedArray){
printf("%c",g.adjMuList[i].vexName);
isVisitedArray[i] = true;
for (int next = firstAdj(g,i); next != -1 ; next = nextAdj(g,i,next)){
if (isVisitedArray[next] == false){
dfs(g,next,isVisitedArray);
}
}
}
//深度优先搜索遍历
void dfsTraver(AMLGraph g){
bool isVisited[MAX_VEX_NUM] = {false};
printf("----------深度优先遍历------------------\n");
for (int i = 0; i < g.vexNum; i++){
if (isVisited[i] == false){
dfs(g,i,isVisited);
}
}
printf("\n");
}
//广度优先搜索遍历
void bfsTraverse(AMLGraph g){
bool isVisited[MAX_VEX_NUM] = {false};
printf("----------广度优先遍历------------------\n");
LinkQueue queue;
queueInit(&queue);
for (int i = 0; i < g.vexNum