上一篇写了DFS的递归方式实现,这次写一下非递归实现。
原理其实非常简单:我用栈去实现的,栈实现的基本思路是将一个节点所有未被访问的“邻居”(即一层层邻居节点)压入栈中“待用”,然后围绕顶部节点猛攻,每个节点访问 后被弹出。下面是实现的代码,仅供参考~
#include <iostream>
#include <stack>
using namespace std;
#define MaxNode 20
#define MAX 20000
int map[MaxNode + 1][MaxNode + 1];
void dfs_stack(int start, int n)
{
int visited[MaxNode], s_top;
for (int i = 0; i <= MaxNode; i++)
{
visited[i] = 0;
}
visited[start] = 1;
stack<int> s;
cout << start << " ";
for (int i = 1; i <=n; i++)
{
if (map[i][start] == 1 && !visited[i])
{
visited[i] = 1;
s.push(i);
}
}
while (!s.empty())
{
s_top = s.top();
visited[s_top] = 1;
cout << s_top << " ";
s.pop();
for (int i = 0; i <= n; i++)
{
if (map[i][s_top] == 1 && !visited[i])
{
visited[i] = 1;
s.push(i);
}
}
}
}
int main(int argc, const char* argv[])
{
int num_edge, num_node;
int x, y;
cout << "Input number of nodes and edges" << endl;
cin >> num_node >> num_edge;
for (int i = 0; i < num_node; i++)
{
for (int j = 0; j < num_node; j++)
{
map[i][j] = 0;
}
}
for (int i = 1; i <= num_edge; i++)
{
cin >> x >> y;
map[x][y] = map[y][x] = 1;
}
dfs_stack(0, num_node);
return 0;
}