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

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

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

给定一个由N个节点和M个边组成的无向图,任务是找到从给定图的每个可能节点经过的从节点 1节点 N的路径的最小长度。如果不存在任何此类路径,则打印-1

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

例子:

方法:这个想法是运行两个 BFS,一个从节点1排除节点N ,另一个从节点N排除节点1 ,以找到所有节点到1N的最小距离。两个最小距离之和将是从1N的路径的最小长度,包括节点。请按照以下步骤解决问题:

  • 初始化一个队列,比如queue1从节点1执行BFS ,队列queue2从节点N执行 BFS。
  • 通过执行BFS1BFS2初始化两个数组,例如dist1[]dist2[]存储最短距离。
  • 执行两次 BFS 并在每种情况下执行以下步骤:
    • 从队列中弹出并将节点存储在x中,并将其距离存储在dis中。
    • 如果dist[x]小于dis然后continue
    • 遍历x和每个子y的邻接列表,如果dist[y]大于dis + 1则更新dist[y]等于dis + 1
  • 在上述步骤中填充两个数组dist1[]dist2[]后,迭代范围[0, N]并且如果(dist1[i] + dist2[i])的总和大于10 9则打印“ -1” ,因为它们不存在这样的路径。否则,打印(dist1[i] + dist2[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 minDisIncludingNode(int n, int m,
                         int edges[][2])
{
    // Vector to store our edges
    vector g[10005];
 
    // Storing the edgees in the 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 > q;
    q.push({ 0, 0 });
    vector dist(n, 1e9);
    dist[0] = 0;
 
    // BFS from first node using queue
    while (!q.empty()) {
        auto up = q.front();
 
        // Pop from queue
        q.pop();
        int x = up.first;
        int lev = up.second;
        if (lev > dist[x])
            continue;
        if (x == n - 1)
            continue;
 
        // Traversing its adjacency list
        for (ll y : g[x]) {
            if (dist[y] > lev + 1) {
                dist[y] = lev + 1;
                q.push({ y, lev + 1 });
            }
        }
    }
    // Initialize queue
    queue > q1;
    q1.push({ n - 1, 0 });
    vector dist1(n, 1e9);
    dist1[n - 1] = 0;
 
    // BFS from last node using queue
    while (!q1.empty()) {
        auto up = q1.front();
 
        // Pop from queue
        q1.pop();
        int x = up.first;
        int lev = up.second;
        if (lev > dist1[x])
            continue;
        if (x == 0)
            continue;
 
        // Traversing its adjacency list
        for (ll y : g[x]) {
            if (dist1[y] > lev + 1) {
                dist1[y] = lev + 1;
                q1.push({ y, lev + 1 });
            }
        }
    }
 
    // Printing the minimum distance
    // including node i
    for (int i = 0; i < n; i++) {
        // If not reachable
        if (dist[i] + dist1[i] > 1e9)
            cout << -1 << " ";
 
        // Path exists
        else
            cout << dist[i] + dist1[i] << " ";
    }
}
 
// Driver Code
int main()
{
    // Given Input
    int n = 5;
    int m = 7;
    int edges[m][2]
        = { { 1, 2 }, { 1, 4 },
            { 2, 3 }, { 2, 5 },
            { 4, 3 }, { 4, 5 },
            { 1, 5 } };
 
    // Function Call
    minDisIncludingNode(n, m, edges);
 
    return 0;
}


Python3
# Python 3 program for the above approach
 
# Function to calculate the distances
# from node 1 to N
def minDisIncludingNode(n, m, edges):
    # Vector to store our edges
    g = [[] for i in range(10005)]
 
    # Storing the edgees in the 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
    q = []
    q.append([0, 0])
    dist = [1e9 for i in range(n)]
    dist[0] = 0
 
    # BFS from first node using queue
    while(len(q)>0):
        up = q[0]
 
        # Pop from queue
        q = q[1:]
        x = up[0]
        lev = up[1]
        if (lev > dist[x]):
            continue
        if (x == n - 1):
            continue
 
        # Traversing its adjacency list
        for y in g[x]:
            if (dist[y] > lev + 1):
                dist[y] = lev + 1
                q.append([y, lev + 1])
             
    # Initialize queue
    q1 = []
    q1.append([n - 1, 0])
    dist1 = [1e9 for i in range(n)]
    dist1[n - 1] = 0
 
    # BFS from last node using queue
    while (len(q1) > 0):
        up = q1[0]
 
        # Pop from queue
        q1 = q1[1:]
        x = up[0]
        lev = up[1]
        if (lev > dist1[x]):
            continue
        if (x == 0):
            continue
 
        # Traversing its adjacency list
        for y in g[x]:
            if (dist1[y] > lev + 1):
                dist1[y] = lev + 1
                q1.append([y, lev + 1])
 
    # Printing the minimum distance
    # including node i
    for i in range(n):
        # If not reachable
        if (dist[i] + dist1[i] > 1e9):
            print(-1,end = " ")
 
        # Path exists
        else:
            print(dist[i] + dist1[i],end = " ")
 
# Driver Code
if __name__ == '__main__':
    # Given Input
    n = 5
    m = 7
    edges = [[1, 2],[1, 4],[2, 3],[2, 5],[4, 3],[4, 5],[1, 5]]
 
    # Function Call
    minDisIncludingNode(n, m, edges)
     
    # This code is contributed by SURENDRA_GANGWAR.


Javascript


输出:
1 2 4 2 1

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