📌  相关文章
📜  包括每个节点的 1 到 N 之间的最小长度路径数

📅  最后修改于: 2022-05-13 01:56:08.670000             🧑  作者: Mango

包括每个节点的 1 到 N 之间的最小长度路径数

给定一个由N个节点和M个边组成的无向无权图,任务是计算节点1N之间通过每个节点的最小长度路径。如果不存在任何这样的路径,则打印“-1”

注意:路径可以通过一个节点任意次数。

例子:

方法:给定问题可以通过执行两个 BFS 来解决,一个从节点1排除节点N ,另一个从节点N排除节点1 ,以找到所有节点到1N的最小距离,以及两个最小距离的乘积将是从1N的最小长度路径的总数,包括节点。请按照以下步骤解决问题:

  • 初始化一个队列,比如queue1从节点1执行BFS ,队列queue2从节点N执行 BFS。
  • 初始化数组,比如dist[]来存储最短距离, ways[]来计算到达该节点的路径数。
  • 执行两次 BFS 并在每种情况下执行以下步骤:
    • 从队列中弹出并将节点存储在x中,并将其距离存储在dis中。
    • 如果dist[x]小于dis然后继续。
    • 遍历x的邻接表,对于每个子y ,如果dist[y]大于dis + 1则更新dist[y]等于dis + 1并且ways[y]等于ways[x] 。否则,如果dist[y]等于dis +1则将ways[x]添加到ways[y]
  • 最后,遍历范围N ,并为每个节点打印最小长度路径的计数为ways1[i]*ways2[i]

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
#define ll long long int
 
// Function to calculate the distances
// from node 1 to N
void countMinDistance(int n, int m,
                      int edges[][2])
{
 
    // Stores the number of edges
    vector g[10005];
 
    // Storing the edges in vector
    for (int i = 0; i < m; i++) {
        int a = edges[i][0] - 1;
        int b = edges[i][1] - 1;
        g[a].push_back(b);
        g[b].push_back(a);
    }
 
    // Initialize queue
    queue > queue1;
    queue1.push({ 0, 0 });
    vector dist(n, 1e9);
    vector ways1(n, 0);
    dist[0] = 0;
    ways1[0] = 1;
 
    // BFS from 1st node using queue
    while (!queue1.empty()) {
        auto up = queue1.front();
 
        // Pop from queue
        queue1.pop();
        int x = up.first;
        int dis = up.second;
        if (dis > dist[x])
            continue;
        if (x == n - 1)
            continue;
 
        // Traversing the adjacency list
        for (ll y : g[x]) {
            if (dist[y] > dis + 1) {
                dist[y] = dis + 1;
                ways1[y] = ways1[x];
                queue1.push({ y, dis + 1 });
            }
            else if (dist[y] == dis + 1) {
                ways1[y] += ways1[x];
            }
        }
    }
 
    // Initialize queue
    queue > queue2;
    queue2.push({ n - 1, 0 });
    vector dist1(n, 1e9);
    vector ways2(n, 0);
    dist1[n - 1] = 0;
    ways2[n - 1] = 1;
 
    // BFS from last node
    while (!queue2.empty()) {
        auto up = queue2.front();
 
        // Pop from queue
        queue2.pop();
        int x = up.first;
        int dis = up.second;
        if (dis > dist1[x])
            continue;
        if (x == 0)
            continue;
 
        // Traverse the adjacency list
        for (ll y : g[x]) {
            if (dist1[y] > dis + 1) {
                dist1[y] = dis + 1;
                ways2[y] = ways2[x];
                queue2.push({ y, dis + 1 });
            }
            else if (dist1[y] == 1 + dis) {
                ways2[y] += ways2[x];
            }
        }
    }
 
    // Print the count of minimum
    // distance
    for (int i = 0; i < n; i++) {
        cout << ways1[i] * ways2[i] << " ";
    }
}
 
// Driver Code
int main()
{
    int N = 5, M = 5;
    int edges[M][2] = {
        { 1, 2 }, { 1, 4 }, { 1, 3 },
        { 2, 5 }, { 2, 4 }
    };
    countMinDistance(N, M, edges);
 
    return 0;
}


Python3
# Python 3 program for the above approach
 
# Function to calculate the distances
# from node 1 to N
def countMinDistance(n, m, edges):
    # Stores the number of edges
    g = [[] for i in range(10005)]
 
    # Storing the edges in vector
    for i in range(m):
        a = edges[i][0] - 1
        b = edges[i][1] - 1
        g[a].append(b)
        g[b].append(a)
 
    # Initialize queue
    queue1 = []
    queue1.append([0, 0])
    dist = [1e9 for i in range(n)]
    ways1 = [0 for i in range(n)]
    dist[0] = 0
    ways1[0] = 1
 
    # BFS from 1st node using queue
    while (len(queue1)>0):
        up = queue1[0]
 
        # Pop from queue
        queue1 = queue1[:-1]
        x = up[0]
        dis = up[1]
        if (dis > dist[x]):
            continue
        if (x == n - 1):
            continue
 
        # Traversing the adjacency list
        for y in g[x]:
            if (dist[y] > dis + 1):
                dist[y] = dis + 1
                ways1[y] = ways1[x]
                queue1.append([y, dis + 1])
         
            elif(dist[y] == dis + 1):
                ways1[y] += ways1[x]
 
    # Initialize queue
    queue2 = []
    queue2.append([n - 1, 0])
    dist1 = [1e9 for i in range(n)]
    ways2 = [0 for i in range(n)]
    dist1[n - 1] = 0
    ways2[n - 1] = 1
 
    # BFS from last node
    while(len(queue2)>0):
        up = queue2[0]
 
        # Pop from queue
        queue2 = queue2[:-1]
        x = up[0]
        dis = up[1]
        if (dis > dist1[x]):
            continue
        if (x == 0):
            continue
 
        # Traverse the adjacency list
        for y in g[x]:
            if (dist1[y] > dis + 1):
                dist1[y] = dis + 1
                ways2[y] = ways2[x]
                queue2.append([y, dis + 1])
 
            elif(dist1[y] == 1 + dis):
                ways2[y] += ways2[x]
 
    # Print the count of minimum
    # distance
    ways1[n-1] = 1
    ways2[n-1] = 1
    for i in range(n):
        print(ways1[i] * ways2[i],end = " ")
     
 
# Driver Code
if __name__ == '__main__':
    N = 5
    M = 5
    edges = [[1, 2],[1, 4],[1, 3],[2, 5],[2, 4]]
    countMinDistance(N, M, edges)
     
    # This code is contributed by SURENDRA_GANGWAR.


Javascript


输出:
1 1 0 1 1

时间复杂度: O(N + M)
辅助空间: O(N)