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] << " ";
}
else
st.pop();
}
}