Program to Find Out if an Edge is a Part of a Minimum Spanning Tree in Python


Suppose we have a 2D matrix named 'edges', that represents an undirected graph. Every item in the matrix 'edges' represents an edge and is of the form (u, v, w). This means nodes u and v are connected and the edge has the weight w. We also have integers a and b, that represent an edge (a,b). We have to find out if the edge (a, b) is part of a minimum spanning tree.

Note − the graph has to be connected and the edge (a, b) exists in the graph.

So, if the input is like edges =

[[0, 2, 100],
[1, 2, 200],
[1, 3, 100],
[2, 3, 300]],
a = 0
b = 2,

then the output will be True.

To solve this, we will follow these steps −

  • Define a function findPath() . This will take edges, a, b

    • if a is same as b, then

      • return True

    • if edges is empty, then

      • return False

    • for each x in edges, do

      • if x[2] is same as -1, then

        • continue the iteration

      • new_a := -1

      • if x[0] is same as a, then

        • new_a := x[1]

      • otherwise when x[1] is same as a, then

        • new_a := x[0]

      • if new_a is not same as -1, then

        • delete x from edges

        • if findPath(edges, new_a, b) is non-zero, then

          • return True

        • insert x at the end of edges

      • return False

Now from the main function, do the following −

  • weight := edge weights of edge x from input array ‘edges’, if

    • ((x[0] is same as a and x[1] is same as b) or(x[1] is same as a and x[0] is same as b))

  • edges := [edge x from input array edges if x[2] <weight]

  • return not findPath(edges, a, b)

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution:
   def findPath(self, edges, a, b):
      if a == b:
         return True
      if not edges:
         return False
      for x in edges:
         if x[2] == -1:
            continue
         new_a = -1
         if x[0] == a:
            new_a = x[1]
         elif x[1] == a:
            new_a = x[0]
         if new_a != -1:
            edges.remove(x)
            if self.findPath(edges, new_a, b):
               return True
            edges.append(x)
      return False
   def solve(self, edges, a, b):
      weight = next(x for x in edges if (x[0] == a and x[1] == b) or (x[1] == a and x[0] == b))[ 2 ]
      edges = [x for x in edges if x[2] < weight]
      return not self.findPath(edges, a, b)

ob = Solution()
print(ob.solve([
   [0, 2, 100],
   [1, 2, 200],
   [1, 3, 100],
   [2, 3, 300]
], 0, 2))

Input

[
[0, 2, 100],
[1, 2, 200],
[1, 3, 100],
[2, 3, 300]
], 0, 2

Output

True

Updated on: 23-Dec-2020

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements