文章目录 1.递归2.非递归 1.递归 void DFS(Graph G, int v) {visited[v] = 1;printf("%c ", G.vexs[v]);for (int i = 0; i < G.vexnum; i++) {if (!visited[i] && G.arcs[v][i]) DFS(G, i);} } 2.非递归 #include <stack> #include <iostream> using namespace std; void DFS(Graph G, int v) {stack<int> st;st.push(v);visited[v] = 1;cout << G.vexs[v] << " ";while (!st.empty()) {int index = 0;bool found = false;//它可能和多个点有边 按照下标递增找到第一个int top = st.top();for (index = 0; index < G.vexnum; index++) {if (!visited[index] && G.arcs[top][index]){found = true;break;}}//但凡找到if (found){st.push(index);visited[index] = 1;cout << G.vexs[index] << " ";}elsest.pop();} }