图的俩种遍历方式(DFS,BFS)C++代码实现

DFS,BFS

代码显示为输出连通集

算法时间复杂度:

采用邻接表存储图:DFS和BFS都为O(N+E)
采用邻接矩阵存储:DFS和BFS都为O(N^2);

数据结构设计

/// @brief 顶点
/// @param adjacencyList 邻接表
struct vertex
{
    int id;
    vector<int> adjacencyList;
};

vector<bool> visited(N,false);
vector<vertex> vertexList(N);

DFS

void dfs(int s,vector<bool>&visited,vector<int>&path,vector<vertex>vertexList)
{
    vector<int> v = vertexList[s].adjacencyList;
    for (int i=0; i<v.size(); ++i)
     {
        if(visited[v[i]]==false)
        {
            path.push_back(v[i]);
            visited[v[i]] = true;
            dfs(v[i], visited, path, vertexList);
        }
    }
}

BFS

void bfs(int s,vector<bool>&visited,vector<int>&path,vector<vertex>vertexList)
{
    queue<int>q;
    q.push(s);
    while (!q.empty()) 
    {
        int cur = q.front();
        q.pop();
        vector<int> v = vertexList[cur].adjacencyList;
        for (int i=0; i<v.size(); ++i) 
        {
            if(visited[v[i]]==false)
            {
                path.push_back(v[i]);
                visited[v[i]] = true;
                q.push(v[i]);
            }
        }
    }
}
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/shizheng163/article/details/51044975
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞