• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
July 14, 2024 |530 Views

PROBLEM OF THE DAY : 13/07/2024 | Shortest Path in Weighted Undirected Graph

Description
Discussion

Welcome to the daily solving of our PROBLEM OF THE DAY with Jay Dalsaniya We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Graph but also build up problem-solving skills.

You are given a weighted undirected graph having n vertices numbered from 1 to n and m edges along with their weights. Find the shortest path between the vertex 1 and the vertex n,  if there exists a path, and return a list of integers whose first element is the weight of the path, and the rest consist of the nodes on that path. If no path exists, then return a list containing a single element -1.

The input list of edges is as follows - {a, b, w}, denoting there is an edge between a and b, and w is the weight of that edge.

Note : Return a list of integers whose first element is the weight of the path, and rest consist of the nodes on that path. The driver code here will first check if the weight of the path returned is equal to the sum of the weights along the nodes on that path, if equal it will output the weight of the path, else -2. In case the list contains only a single element [-1] it will simply output -1

Examples :

Input: n = 5, m= 6, edges = [[1,2,2], [2,5,5], [2,3,4], [1,4,1], [4,3,3], [3,5,1]]
Output: 5
Explanation: Shortest path from 1 to n is by the path 1 4 3 5 whose weight is 5. 

Give the problem a try before going through the video. All the best!!!
Problem Link: https://practice.geeksforgeeks.org/problems/shortest-path-in-weighted-undirected-graph/1