📜  不使用队列的广度优先搜索

📅  最后修改于: 2021-10-25 04:48:37             🧑  作者: Mango

广度优先搜索是一种图遍历算法,它逐层遍历图或树。在本文中,图的 BFS 是使用邻接表实现的,而不使用队列。
例子:

方法:这个问题可以使用来自给定源的简单广度优先遍历来解决。该实现使用图的邻接列表表示
这里:

  • STL Vector 容器用于存储 BFS 遍历所需的相邻节点列表和节点队列。
  • DP 数组用于存储节点与源的距离。每次我们从一个节点移动到另一个节点时,距离增加 1。如果到达节点的距离比之前的距离小,我们更新存储在 DP[node] 中的值。

下面是上述方法的实现:

CPP
// C++ implementation to demonstrate
// the above mentioned approach
 
#include 
using namespace std;
 
// Function to find the distance
// from the source to other nodes
void BFS(int curr, int N, vector& vis,
         vector& dp, vector& v,
         vector >& adj)
{
 
    while (curr <= N) {
 
        // Current node
        int node = v[curr - 1];
        cout << node << ", ";
 
        for (int i = 0; i < adj[node].size(); i++) {
 
            // Adjacent node
            int next = adj[node][i];
 
            if ((!vis[next])
                && (dp[next] < dp[node] + 1)) {
 
                // Stores the adjacent node
                v.push_back(next);
 
                // Increases the distance
                dp[next] = dp[node] + 1;
 
                // Mark it as visited
                vis[next] = true;
            }
        }
        curr += 1;
    }
}
 
// Function to print the distance
// from source to other nodes
void bfsTraversal(
    vector >& adj,
    int N, int source)
{
    // Initially mark all nodes as false
    vector vis(N + 1, false);
 
    // Initialize distance array with 0
    vector dp(N + 1, 0), v;
 
    v.push_back(source);
 
    // Initially mark the starting
    // source as 0 and visited as true
    dp = 0;
    vis = true;
 
    // Call the BFS function
    BFS(1, N, vis, dp, v, adj);
}
 
// Driver code
int main()
{
    // No. of nodes in graph
    int N = 4;
 
    // Creating adjacency list
    // for representing graph
    vector > adj(N + 1);
    adj[0].push_back(1);
    adj[0].push_back(2);
    adj[1].push_back(2);
    adj[2].push_back(0);
    adj[2].push_back(3);
    adj[3].push_back(3);
 
    // Following is BFS Traversal
    // starting from vertex 2
    bfsTraversal(adj, N, 2);
 
    return 0;
}


输出:
2, 0, 3, 1,

时间复杂度: O(V + E),其中 V 是顶点数,E 是边数。
辅助空间: O(V)