
树的深度优先遍历
树的深度优先遍历分为先根遍历和后根遍历。
图的深度优先遍历

代码(只能遍历连通图)
cpp
//深度优先遍历
void DFS(Graph G, int v) {//从顶点v出发,深度优先遍历图G
visit(v);//访问初始顶点v
visited[v] = true;//对v做已访问标记
for (w = FirsitNeighbor(G, v); w >= 0; w = NextNeighbor(G, v, w);)
//检查v所有邻接点
if (!visited[w]) {//w为v的尚未访问的邻接点
DFS(G, w);
}
}
DFS算法(Final版)

代码
cs
void DFSTraverse(Graph G) {//对图G进行深度优先遍历
for (int v = 0; v < G.vexnum; ++v)
visited[v] = false;//访问标记数组初始化
for (int v = 0; v < G.vexnum; ++v)//从0号顶点开始遍历
if (!visited[v])//对每个连通分量调用一次BFS
DFS(G, v);//vi未访问过,从vi开始BFS
}
//深度优先遍历
void DFS(Graph G, int v) {//从顶点v出发,深度优先遍历图G
visit(v);//访问初始顶点v
visited[v] = true;//对v做已访问标记
for (w = FirsitNeighbor(G, v); w >= 0; w = NextNeighbor(G, v, w);)
//检查v所有邻接点
if (!visited[w]) {//w为v的尚未访问的邻接点
DFS(G, w);
}
}
复杂度分析
空间复杂度

时间复杂度

深度优先遍历练习



深度优先生成树


深度优先生成森林


图的遍历和图的连通性
无向图

有向图

总结:
