Program to find minimum number of buses required to reach final target in python

PythonServer Side ProgrammingProgramming

Suppose we have a n x 3 matrix where each row contains three fields [src, dest, id] this means the bus has route from src to dest. It takes one unit of money to get on a new bus, but if we stay on the same bus we have to pay one unit only. We have to find the minimum cost necessary to take the bus from location 0 to the final stop (largest location). If there is no solution return -1.

So, if the input is like

0
1
0
1
2
0
2
3
0
3
5
1
5
0
2

then the output will be 2, as we can take the 0 at location 0 and get out at location 3. Then we take the bus 1 to reach location 5.

To solve this, we will follow these steps −

  • start := 0
  • target := maximum place of given matrix
  • adj := an empty map
  • for each src, dest, id in connections, do
    • insert (dest, id) at the end of adj[src]
  • hp := a heap with item (0, start, -1)
  • seen := an empty map
  • while hp is not empty, do
    • (cost, cur_pos, cur_bus) := top element of heap hp and delete top from hp
    • if cur_pos is same as target, then
      • return cost
    • if cur_bus in seen[cur_pos], then
      • go for the next iteration
    • insert cur_bus into seen[cur_pos]
    • for each (nex_pos, nex_bus) in adj[cur_pos], do
      • next_cost := cost
      • if nex_bus is not same as cur_bus, then
        • next_cost := next_cost + 1
      • insert (next_cost, nex_pos, nex_bus) into heap hp
  • return -1

Let us see the following implementation to get better understanding −

Example 

Live Demo

from collections import defaultdict
from heapq import heapify, heappop, heappush
class Solution:
   def solve(self, connections):
      start = 0
      target = max(max(y, x) for y, x, _ in connections)

      adj = defaultdict(list)
      for f, t, id in connections:
         adj[f].append((t, id))

      hp = [(0, start, -1)]
      seen = defaultdict(set)

      while hp:
         cost, cur_pos, cur_bus = heappop(hp)
         if cur_pos == target:
            return cost
         if cur_bus in seen[cur_pos]:
            continue
         seen[cur_pos].add(cur_bus)

         for nex_pos, nex_bus in adj[cur_pos]:
            next_cost = cost
            if nex_bus != cur_bus:
               next_cost += 1
            heappush(hp, (next_cost, nex_pos, nex_bus))

      return -1

ob = Solution()
matrix = [
   [0, 1, 0],
   [1, 2, 0],
   [2, 3, 0],
   [3, 5, 1],
   [5, 0, 2]
]
print(ob.solve(matrix))

Input

matrix = [[0, 1, 0],  
[1, 2, 0],  
[2, 3, 0],  
[3, 5, 1],  
[5, 0, 2]]

Output

2
raja
Published on 03-Dec-2020 05:38:02
Advertisements