深度优先遍历(递归和非递归实现)

深度优先搜索(Depth-First-Search,简称DFS)。这是一种常见的用于遍历或搜索树或者图的算法。

基本实现思想:
(1)访问顶点v;
(2)从v的未被访问的邻接点中选取一个顶点w,从w出发进行深度优先遍历;
(3)重复上述两步,直至图中所有和v有路径相通的顶点都被访问到。


#include <vector>
#include <queue>
#include <stack>
#include <iostream>
using namespace std;

//

//初始化图参数

int iSize = 6;
char cVertex[] = { 'A','B','C','D','E','F' };
bool bAdj[] = { 0,1,1,1,0,0, 1,0,0,0,1,0, 1,0,0,0,0,1, 1,0,0,0,0,0, 0,1,0,0,0,1, 0,0,1,0,1,0 };

bool bVisited[6 * 6];

//深度优先遍历(递归实现)

void depthFirstTraversal(int v)
{
    if (v < 0 || v >= iSize)
    {
        return;
    }
    cout << cVertex[v]<<"\t";
    bVisited[v] = true;
    for (int i = 0; i < iSize; i++)
    {
        if (bVisited[i] == false && bAdj[v*iSize + i] == true)
        {
            depthFirstTraversal(i);
        }
    }
}

//深度优先遍历(非递归实现),对于循环实现,需要用到栈结构

void depthFirstTraversalByLoop(int v)

{
    stack<int> s;
    s.push(v);
    cout << cVertex[v] << "\t";
    bVisited[v] = true;
    while (s.size())
    {
        int index = s.top();
        int flag = false;
        for (int i = 0; i < iSize; i++)
        {
            if (bVisited[i] == false && bAdj[index*iSize + i] == true)
            {
                s.push(i);
                cout << cVertex[i] << "\t";
                bVisited[i] = true;
                flag = true;
                break;
            }
        }
        if (flag==false)
        {
            s.pop();
        }
    }

}

int main()
{
     //memset(adj, false, sizeof(bool) * 25);
    memset(bVisited, false, sizeof(bool) * 25);
    //depthFirstTraversal(0);
    depthFirstTraversalByLoop(0);
    return 0;
}


猜你喜欢

转载自blog.csdn.net/u010757019/article/details/80958392