📜  门| GATE 2017 MOCK II |问题 10(1)

📅  最后修改于: 2023-12-03 14:58:17.788000             🧑  作者: Mango

GATE 2017 MOCK II - Question 10

Introduction

This is a programming question from the GATE 2017 MOCK II exam. It examines the knowledge and skills of the programmer in implementing data structures and algorithms.

Problem Statement

We are given a graph G=(V,E) with n vertices and m edges, and its adjacency matrix A of size n × n. We need to compute the sum of distances between every pair of nodes in the graph. The distance between two nodes is defined as the length of the shortest path between them.

Approach

To solve this problem, we can use the Floyd-Warshall algorithm. It is a classic algorithm in graph theory that computes the shortest path between all pairs of nodes in a weighted graph.

The Floyd-Warshall algorithm works by considering all possible intermediate vertices in a path from i to j. For each pair of vertices i and j, the algorithm computes the shortest path that passes through all the vertices from 1 to k−1, where k is an intermediate vertex that is being considered. The algorithm updates the distance between i and j as the minimum of the distance between i and j without considering k, and the distance through k. This is done for all pairs of vertices i and j, and all possible intermediate vertices k.

We can implement the Floyd-Warshall algorithm using a triple-nested loop to consider all pairs of vertices and all possible intermediate vertices. The time complexity of the algorithm is O(n^3).

Code

Here is an implementation of the Floyd-Warshall algorithm in Python:

def floyd_warshall(A):
    n = len(A)
    dist = [[float('inf')] * n for i in range(n)]
    for i in range(n):
        for j in range(n):
            if A[i][j]:
                dist[i][j] = A[i][j]
    for k in range(n):
        for i in range(n):
            for j in range(n):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
    return sum(sum(dist[i]) for i in range(n))

# Test the implementation
A = [
    [0, 2, 5],
    [2, 0, 7],
    [5, 7, 0]
]
assert floyd_warshall(A) == 32

In the code, we first initialize an n × n distance matrix dist with all values set to infinity. We then set the distances between adjacent vertices in the graph to their corresponding values in the adjacency matrix A. We then use a triple-nested loop to iterate over all pairs of vertices and all possible intermediate vertices, and update the distance matrix dist as described above. Finally, we compute and return the sum of all distances in the matrix.

Conclusion

In this question, we have explored the Floyd-Warshall algorithm for computing the sum of distances between all pairs of nodes in a graph. We have implemented the algorithm in Python and shown how it can be used to solve the problem. The algorithm has a time complexity of O(n^3), and is a classic algorithm in graph theory that is widely used in many applications.