DFS非递归写法

1、介绍

从根结点开始,彻底搜索每一个分支直到它们的最深处,然后再返回到先前未搜索过的分支(搜索顺序。搜索过程中遇到的结点保存在一个后进先出队列(LIFO,即堆栈)中,该队列将会被再次访问。
下面是例子
节点

2、代码

#include<iostream>
#include<stack>
#include<memory.h>

using namespace std;
int graph[9][9];//定义一个简单的邻接矩阵
int nodes = 8;//节点的数量

//深度优先搜索函数
void dfs(int root,int goal)
{
    stack<int>_stack;
    _stack.push(root);//将根节点压入栈中
    while (!_stack.empty())
    {
        int cur = _stack.top();//拿出栈顶的节点
        _stack.pop();
        cout << cur << " ";
        if (cur == goal)break;//如果是目标节点则结束寻找
        for (int i = 1; i <= nodes; i++)//考察邻接节点,压入堆栈
        {
            if (graph[cur][i] == 1)
                _stack.push(i);
        }
    }
}

//初始化图
void init_graph( int(&g)[9][9] )
{
    memset(graph, 0, sizeof(graph));
    graph[1][2] = 1;
    graph[1][6] = 1;
    graph[2][3] = 1;
    graph[6][7] = 1;
    graph[6][8] = 1;
    graph[3][4] = 1;
    graph[3][5] = 1;
}

int main()
{
    int root = 1;
    int goal;
    cin >> goal;
    init_graph(graph);
    dfs(root, goal);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wayway0554/article/details/80258993