Shortest Distance in a graph with two different weights

Given a weighted undirected graph having A nodes.
A matrix B of size M x 3 is given which represents the edges such that there is an edge between
B[i][0] and B[i][1] having weight B[i][2].
B[i][2] can be either 1 or 2.
Given a source node C and a destination node D.

Find the shortest distance from C to D. If it is impossible to reach node D from C then return -1.

You are expected to do it in Time Complexity of O(A + M).

Note:

  1. There are no self-loops in the graph.

  2. No multiple edges between two pair of vertices.

  3. The graph may or may not be connected.

  4. Nodes are Numbered from 0 to A-1.

  5. Your solution will run on multiple testcases. If you are using global variables make sure to clear them.



Input Format

The first argument given is an integer A.
The second argument given is the matrix B.
The third argument given is an integer C.
The fourth argumnet is an integer D. 

Output Format

Return the shortest distance from C to D. If it is impossible to reach node D from C then return -1.

Constraints

1 <= A <= 100000
0 <= B[i][0], B[i][1] < A
1 <= B[i][2] <= 2;
0 <= C < A
0 <= D < A

For Example

Input 1:
    A = 6
    B = [   [2, 5, 1]
            [1, 3, 1] 
            [0, 5, 2] 
            [0, 2, 2] 
            [1, 4, 1] 
            [0, 1, 1] ] 
    C = 3
    D = 2
Output 1:
    4

Input 2:
    A = 5
    B = [   [0, 2, 1]
            [0, 4, 2] 
            [1, 3, 1]
            [1, 4, 1]
            [0, 1, 1] 
            [2, 4, 1]
            [3, 4, 2] 
            [1, 2, 1]  ] 
    C = 1
    D = 3
Output 2:
    1
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Shortest Distance in a graph with two different weights  on Interview Code Editor
Sign Up
to access hints and editorial solutions for Shortest Distance in a graph with two different weights

Discussion


Loading...
Click here to start solving coding interview questions