The Wayback Machine - https://web.archive.org/web/20241128150832/https://www.geeksforgeeks.org/maximize-shortest-path-between-given-vertices-by-adding-a-single-edge/
Open In App

Maximize shortest path between given vertices by adding a single edge

Last Updated : 10 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an undirected graph of N nodes and M vertices. You are also given a K edges as selected[]. The task to maximize the shortest path length between node 1 to node N by adding single edges between any two vertices from the given selected edges. 
Note: You may add an edge between any two selected vertices who have already an edge between them.

Input: N = 5, M = 4, K = 2, selected[] = {2, 4} 
Below is the given graph: 
 

Output: 3 
Explanation: 
Before adding an edge between 2 and 4, the Shortest Path becomes: 1–>2–>3–>4–>5. 
After adding an edge between 2 and 4, the Shortest Path becomes 1–>2–>4–>5. Below is the graph after adding edges. denoted by the dashed line. 
 

Input: N = 5 M = 5 K = 3 selected[] = {1, 3, 5} 
Below is the given graph: 
 

Output: 3 
Explanation: 
We can add an edge between 3 and 5 as they have already an edge between them. so, the shortest path becomes 1–>2–>3–>5. Below is the graph after adding edges. denoted by the dashed line. 
 

 

 

Approach: The idea is to use Breadth-First Search to find the distance from vertices 1 and N to each selected vertex. For selected vertex i, let xi denote the distance to node 1, and yi denote the distance to node N. Below are the steps:

  1. Maintain a 2D matrix(say dist[2][]) having 2 rows and N columns.
  2. In the first row, Maintain the shortest distance between node 1 and other vertices in the graph using BFS Traversal.
  3. In the second row, Maintain the shortest distance between node N and the other vertices of the graph using BFS Traversal.
  4. Now, choose two selected vertices a and b from selected[] to minimize the value of min(xa + yb, ya + xb). For this do the following: 
    • Create a vector of pairs and store the value of (xi – yi) with their respective selected node.
    • Sort the above vector of pairs.
    • Initialize best to 0 and max to -INF.
    • Now traverse the above vector of pairs and for each selected node(say a) update the value of best to maximum of (best, max + dist[1][a]) and update max to maximum of (max, dist[0][a]).
  5. After the above operations the maximum of (dist[0][N-1] and best + 1) given the minimum shortest path.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
int N, M;
 
// To store graph as adjacency list
vector<int> edges[200005];
 
// To store the shortest path
int dist[2][200000];
 
// Function that performs BFS Traversal
void bfs(int* dist, int s)
{
    int q[200000];
 
    // Fill initially each distance as INF
    fill(dist, dist + N, INF);
    int qh = 0, qt = 0;
    q[qh++] = s;
    dist[s] = 0;
 
    // Perform BFS
    while (qt < qh) {
 
        int x = q[qt++];
 
        // Traverse the current edges
        for (int y : edges[x]) {
            if (dist[y] == INF) {
 
                // Update the distance
                dist[y] = dist[x] + 1;
 
                // Insert in queue
                q[qh++] = y;
            }
        }
    }
}
 
// Function that maximizes the shortest
// path between source and destination
// vertex by adding a single edge between
// given selected nodes
void shortestPathCost(int selected[], int K)
{
    vector<pair<int, int> > data;
 
    // To update the shortest distance
    // between node 1 to other vertices
    bfs(dist[0], 0);
 
    // To update the shortest distance
    // between node N to other vertices
    bfs(dist[1], N - 1);
 
    for (int i = 0; i < K; i++) {
 
        // Store the values x[i] - y[i]
        data.emplace_back(dist[0][selected[i]]
                              - dist[1][selected[i]],
                          selected[i]);
    }
 
    // Sort all the vectors of pairs
    sort(data.begin(), data.end());
    int best = 0;
    int MAX = -INF;
 
    // Traverse data[]
    for (auto it : data) {
        int a = it.second;
        best = max(best,
                   MAX + dist[1][a]);
 
        // Maximize x[a] - y[b]
        MAX= max(MAX, dist[0][a]);
    }
 
    // Print minimum cost
    printf("%d\n", min(dist[0][N - 1], best + 1));
}
 
// Driver Code
int main()
{
    // Given nodes and edges
    N = 5, M = 4;
    int K = 2;
    int selected[] = { 1, 3 };
 
    // Sort the selected nodes
    sort(selected, selected + K);
 
    // Given edges
    edges[0].push_back(1);
    edges[1].push_back(0);
    edges[1].push_back(2);
    edges[2].push_back(1);
    edges[2].push_back(3);
    edges[3].push_back(2);
    edges[3].push_back(4);
    edges[4].push_back(3);
 
    // Function Call
    shortestPathCost(selected, K);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
     
static int INF = (int)1e9 + 7;
static int N, M;
   
// To store graph as adjacency list
static ArrayList<ArrayList<Integer>> edges;
   
// To store the shortest path
static int[][] dist = new int[2][200000];
   
// Function that performs BFS Traversal
static void bfs(int[] dist, int s)
{
    int[] q = new int[200000];
   
    // Fill initially each distance as INF
    Arrays.fill(dist, INF);
     
    int qh = 0, qt = 0;
    q[qh++] = s;
    dist[s] = 0;
   
    // Perform BFS
    while (qt < qh)
    {
        int x = q[qt++];
   
        // Traverse the current edges
        for(Integer y : edges.get(x))
        {
            if (dist[y] == INF)
            {
                 
                // Update the distance
                dist[y] = dist[x] + 1;
   
                // Insert in queue
                q[qh++] = y;
            }
        }
    }
}
   
// Function that maximizes the shortest
// path between source and destination
// vertex by adding a single edge between
// given selected nodes
static void shortestPathCost(int selected[], int K)
{
    ArrayList<int[]> data = new ArrayList<>();
   
    // To update the shortest distance
    // between node 1 to other vertices
    bfs(dist[0], 0);
   
    // To update the shortest distance
    // between node N to other vertices
    bfs(dist[1], N - 1);
   
    for(int i = 0; i < K; i++)
    {
         
        // Store the values x[i] - y[i]
        data.add(new int[]{dist[0][selected[i]] -
                           dist[1][selected[i]],
                                   selected[i]});
    }
   
    // Sort all the vectors of pairs
    Collections.sort(data, (a, b) -> a[0] - b[0]);
    int best = 0;
    int MAX = -INF;
   
    // Traverse data[]
    for(int[] it : data)
    {
        int a = it[1];
        best = Math.max(best,
                        MAX + dist[1][a]);
   
        // Maximize x[a] - y[b]
        MAX = Math.max(MAX, dist[0][a]);
    }
     
    // Print minimum cost
    System.out.println(Math.min(dist[0][N - 1],
                                     best + 1));
}
 
// Driver code
public static void main (String[] args)
{
     
    // Given nodes and edges
    N = 5; M = 4;
    int K = 2;
    int selected[] = { 1, 3 };
     
    // Sort the selected nodes
    Arrays.sort(selected);
     
    edges = new ArrayList<>();
     
    for(int i = 0; i < 200005; i++)
        edges.add(new ArrayList<Integer>());
     
    // Given edges
    edges.get(0).add(1);
    edges.get(1).add(0);
    edges.get(1).add(2);
    edges.get(2).add(1);
    edges.get(2).add(3);
    edges.get(3).add(2);
    edges.get(3).add(4);
    edges.get(4).add(3);
     
    // Function Call
    shortestPathCost(selected, K);
}
}
 
// This code is contributed by offbeat


Python3




# Python3 program for the above approach
 
# Function that performs BFS Traversal
def bfs(x, s):
    global edges, dist
    q = [0 for i in range(200000)]
 
    # Fill initially each distance as INF
    # fill(dist, dist + N, INF)
    qh, qt = 0, 0
    q[qh] = s
    qh += 1
    dist[x][s] = 0
 
    # Perform BFS
    while (qt < qh):
        xx = q[qt]
        qt += 1
 
        # Traverse the current edges
        for y in edges[xx]:
            if (dist[x][y] == 10**18):
 
                # Update the distance
                dist[x][y] = dist[x][xx] + 1
 
                # Insert in queue
                q[qh] = y
                qh += 1
 
# Function that maximizes the shortest
# path between source and destination
# vertex by adding a single edge between
# given selected nodes
def shortestPathCost(selected, K):
    global dist, edges
    data = []
 
    # To update the shortest distance
    # between node 1 to other vertices
    bfs(0, 0)
 
    # To update the shortest distance
    # between node N to other vertices
    bfs(1, N - 1)
    for i in range(K):
 
        # Store the values x[i] - y[i]
        data.append([dist[0][selected[i]]- dist[1][selected[i]], selected[i]])
 
    # Sort all the vectors of pairs
    data = sorted(data)
    best = 0
    MAX = -10**18
 
    # Traverse data[]
    for it in data:
        a = it[1]
        best = max(best,MAX + dist[1][a])
 
        # Maximize x[a] - y[b]
        MAX= max(MAX, dist[0][a])
 
    # Print minimum cost
    print(min(dist[0][N - 1], best + 1))
 
# Driver Code
if __name__ == '__main__':
 
    # Given nodes and edges
    edges = [[] for i in range(5)]
    dist = [[10**18 for i in range(1000005)] for i in range(2)]
    N,M = 5, 4
    K = 2
    selected = [1, 3]
 
    # Sort the selected nodes
    selected = sorted(selected)
 
    # Given edges
    edges[0].append(1)
    edges[1].append(0)
    edges[1].append(2)
    edges[2].append(1)
    edges[2].append(3)
    edges[3].append(2)
    edges[3].append(4)
    edges[4].append(3)
 
    # Function Call
    shortestPathCost(selected, K)
 
    # This code is contributed by mohit kumar 29


C#




using System;
using System.Linq;
 
class Program
{
    static int N, M, K;
    static int[][] edges, dist;
    static int[] selected;
//Function that performs BFS Traversal
    static void BFS(int x, int s)
    {
        int[] q = new int[200000];
        //
    //Fill initially each distance as INF
    //fill(dist, dist + N, INF)
        int qh = 0, qt = 0;
 
        q[qh] = s;
        qh++;
        dist[x][s] = 0;
//Perform BFS
        while (qt < qh)
        {
            int xx = q[qt];
            qt++;
 
            for (int i = 0; i < edges[xx].Length; i++)
            {
                int y = edges[xx][i];
                if (dist[x][y] == int.MaxValue)
                {
                    dist[x][y] = dist[x][xx] + 1;
                    q[qh] = y;
                    qh++;
                }
            }
        }
    }
  //  Function that maximizes the shortest
// path between source and destination
// vertex by adding a single edge between
// given selected nodes
 
    static void ShortestPathCost(int[] selected, int K)
    {
        BFS(0, 0);
        BFS(1, N - 1);
 
        Tuple<int, int>[] data = new Tuple<int, int>[K];
        for (int i = 0; i < K; i++)
        {
            data[i] = Tuple.Create(dist[0][selected[i]] - dist[1][selected[i]], selected[i]);
        }
 
        Array.Sort(data, (a, b) => a.Item1.CompareTo(b.Item1));
 
        int best = 0, MAX = int.MinValue;
        foreach (Tuple<int, int> it in data)
        {
            int a = it.Item2;
            best = Math.Max(best, MAX + dist[1][a]);
            MAX = Math.Max(MAX, dist[0][a]);
        }
 
        Console.WriteLine(Math.Min(dist[0][N - 1], best + 1));
    }
//Driver code
    static void Main(string[] args)
    {
        N = 5;
        M = 4;
        K = 2;
        selected = new int[] { 1, 3 };
 
        Array.Sort(selected);
 
        edges = new int[5][];
        edges[0] = new int[] { 1 };
        edges[1] = new int[] { 0, 2 };
        edges[2] = new int[] { 1, 3 };
        edges[3] = new int[] { 2, 4 };
        edges[4] = new int[] { 3 };
 
        dist = new int[2][];
        dist[0] = Enumerable.Repeat(int.MaxValue, 1000005).ToArray();
        dist[1] = Enumerable.Repeat(int.MaxValue, 1000005).ToArray();
 
        ShortestPathCost(selected, K);
    }
}


Javascript




<script>
// Javascript program for the above approach
 
let INF = 1e9 + 7;
let N, M;
 
// To store graph as adjacency list
let  edges=[];
 
// To store the shortest path
let dist=new Array(2);
for(let i=0;i<2;i++)
{
    dist[i]=new Array(200000);
    for(let j=0;j<200000;j++)
    {
        dist[i][j]=INF;
    }
}
 
// Function that performs BFS Traversal
function bfs(dist,s)
{
    let q = new Array(200000);
    
    // Fill initially each distance as INF
     
      
    let qh = 0, qt = 0;
    q[qh++] = s;
    dist[s] = 0;
    
    // Perform BFS
    while (qt < qh)
    {
        let x = q[qt++];
    
        // Traverse the current edges
        for(let y=0;y< edges[x].length;y++)
        {
            if (dist[edges[x][y]] == INF)
            {
                  
                // Update the distance
                dist[edges[x][y]] = dist[x] + 1;
    
                // Insert in queue
                q[qh++] = edges[x][y];
            }
        }
    }
}
 
// Function that maximizes the shortest
// path between source and destination
// vertex by adding a single edge between
// given selected nodes   
function shortestPathCost(selected,K)
{
    let data = [];
    
    // To update the shortest distance
    // between node 1 to other vertices
    bfs(dist[0], 0);
    
    // To update the shortest distance
    // between node N to other vertices
    bfs(dist[1], N - 1);
    
    for(let i = 0; i < K; i++)
    {
          
        // Store the values x[i] - y[i]
        data.push([dist[0][selected[i]] -
                           dist[1][selected[i]],
                                   selected[i]]);
    }
    
    // Sort all the vectors of pairs
    data.sort(function(a, b){return a[0] - b[0];});
    let best = 0;
    let MAX = -INF;
    
    // Traverse data[]
    for(let it=0;it< data.length;it++)
    {
        let a = data[it][1];
        best = Math.max(best,
                        MAX + dist[1][a]);
    
        // Maximize x[a] - y[b]
        MAX = Math.max(MAX, dist[0][a]);
    }
      
    // Print minimum cost
    document.write(Math.min(dist[0][N - 1],
                                     best + 1));
}
 
// Driver code
// Given nodes and edges
    N = 5; M = 4;
    let K = 2;
    let selected = [ 1, 3 ];
      
    // Sort the selected nodes
    (selected).sort(function(a,b){return a-b;});
      
    edges = [];
      
    for(let i = 0; i < 200005; i++)
        edges.push([]);
      
    // Given edges
    edges[0].push(1);
    edges[1].push(0);
    edges[1].push(2);
    edges[2].push(1);
    edges[2].push(3);
    edges[3].push(2);
    edges[3].push(4);
    edges[4].push(3);
      
    // Function Call
    shortestPathCost(selected, K);
 
// This code is contributed by patel2127
</script>


Output: 

3

 

Time Complexity: O(N*log N + M) 
Auxiliary Space: O(N) 
 

 



Previous Article
Next Article

Similar Reads

Maximize the number of uncolored vertices appearing along the path from root vertex and the colored vertices
Given a tree with N vertices numbered 1 through N with vertex 1 as root vertex and N - 1 edges. We have to color exactly k number of vertices and count the number of uncolored vertices between root vertex and every colored vertex. We have to include the root vertex in the count if it is not colored. The task to maximize the number of uncolored vert
8 min read
Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
Given a connected graph with N vertices and M edges. The task is to find the shortest path from source to the destination vertex such that the difference between adjacent edge weights in the shortest path change from positive to negative and vice versa ( Weight(E1) > Weight(E2) < Weight(E3) .... ). If no such path exists then print -1. Exampl
13 min read
Find all remaining vertices in Graph after marking shortest path for neighbours
Given an undirected graph with V vertices in the form of an adjacency matrix, the weight of any two edges cannot be the same. For each vertex mark vertex that is connected to it via the edge of the lowest weight, the task is to return all the unmarked vertices. Return -1 if every vertex is marked. Examples: Input: V = 3, A[][] = {{0, 10, 50}, {10,
7 min read
Difference between the shortest and second shortest path in an Unweighted Bidirectional Graph
Given an unweighted bidirectional graph containing N nodes and M edges represented by an array arr[][2]. The task is to find the difference in length of the shortest and second shortest paths from node 1 to N. If the second shortest path does not exist, print 0. Note: The graph is connected, does not contain multiple edges and self loops. (2<=N
15+ min read
Time saved travelling in shortest route and shortest path through given city
Given a matrix mat[][] of size N * N, where mat[i][j] represents the time taken to reach from ith city to jth city. Also, given M queries in the form of three arrays S[], I[], and D[] representing source, intermediate, and destination respectively. The task is to find the time taken to go from S[i] to D[i] using I[i] city and the time that can be s
10 min read
Find the remaining vertices of a square from two given vertices
Given the coordinates of any two vertices of a square (X1, Y1) and (X2, Y2), the task is to find the coordinates of the other two vertices. If a square cannot be formed using these two vertices, print -1.The sides of the square must be parallel to either the x-axis or the y-axis. Examples: Input: X1 = 1, Y1 = 2, X2 = 3, Y2 = 4 Output: (1, 4), (3, 2
7 min read
Single source shortest path between two cities
Given a graph of N Nodes and E edges in form of {U, V, W} such that there exists an edge between U and V with weight W. You are given an integer K and source src and destination dst. The task is to find the cheapest cost path from given source to destination from K stops.Examples: Input: N = 3, edges = [[0, 1, 100], [1, 2, 100], [0, 2, 500]], src =
15+ min read
Shortest path with one curved edge in an undirected Graph
Given an undirected connected graph of n vertices and a list of m edges in a graph and for each pair of vertices that are connected by an edge. There are two edges between them, one curved edge and one straight edge i.e. the tuple (x, y, w1, w2) means that between vertices x and y, there is a straight edge with weight w1 and a curved edge with weig
13 min read
Shortest Path in a weighted Graph where weight of an edge is 1 or 2
Given a directed graph where every edge has weight as either 1 or 2, find the shortest path from a given source vertex ‘s’ to a given destination vertex ‘t’. Expected time complexity is O(V+E). A Simple Solution is to use Dijkstra’s shortest path algorithm, we can get a shortest path in O(E + VLogV) time. How to do it in O(V+E) time? The idea is to
15 min read
Shortest Path Using Atmost One Curved Edge
Given an undirected connected graph of n vertices and a list of m edges in a graph and for each pair of vertices that are connected by an edge. There are two edges between them, one curved edge and one straight edge i.e. the tuple (x, y, w1, w2) means that between vertices x and y, there is a straight edge with weight w1 and a curved edge with weig
13 min read
Find the path from root to a vertex such that all K vertices belongs to this path or 1 distance away
Given a tree consisting of N vertices numbered from 1 to N rooted at vertex 1. You are given Q queries. Each query consists of the set of K distinct vertices vi[1], vi[2],…, vi[K]. The task is to determine if there is a path from the root to some vertex X such that each of the given K vertices either belongs to this path or has the distance 1 to so
10 min read
Minimum number of edges to be removed from given Graph such that no path exists between given pairs of vertices
Given an undirected graph consisting of N valued over the range [1, N] such that vertices (i, i + 1) are connected and an array arr[] consisting of M pair of integers, the task is to find the minimum number of edges that should be removed from the graph such that there doesn't exist any path for every pair (u, v) in the array arr[]. Examples: Input
8 min read
Find K vertices in the graph which are connected to at least one of remaining vertices
Given a connected graph with N vertices. The task is to select k(k must be less than or equals to n/2, not necessarily minimum) vertices from the graph such that all these selected vertices are connected to at least one of the non selected vertex. In case of multiple answers print any one of them. Examples: Input : Output : 1 Vertex 1 is connected
8 min read
Find three vertices in an N-sided regular polygon such that the angle subtended at a vertex by two other vertices is closest to A
Given an N-sided regular convex polygon and an angle A in degrees, the task is to find any 3 vertices i, j, and k, such that the angle subtended at vertex j by vertex i and k is closest to A. Note: Each vertex is numbered from 1 to N in an anticlockwise direction starting from any vertex. Examples: Input: N = 3, A = 15Output: 2 1 3Explanation:The g
7 min read
Pendant Vertices, Non-Pendant Vertices, Pendant Edges and Non-Pendant Edges in Graph
Pre-requisites: Handshaking theorem. Pendant Vertices Let G be a graph, A vertex v of G is called a pendant vertex if and only if v has degree 1. In other words, pendant vertices are the vertices that have degree 1, also called pendant vertex. Note: Degree = number of edges connected to a vertex In the case of trees, a pendant vertex is known as a
7 min read
Find maximum number of edge disjoint paths between two vertices
Given a directed graph and two vertices in it, source 's' and destination 't', find out the maximum number of edge disjoint paths from s to t. Two paths are said edge disjoint if they don't share any edge. There can be maximum two edge disjoint paths from source 0 to destination 7 in the above graph. Two edge disjoint paths are highlighted below in
15+ min read
Shortest path to reach one prime to other by changing single digit at a time
Given two four digit prime numbers, suppose 1033 and 8179, we need to find the shortest path from 1033 to 8179 by altering only single digit at a time such that every number that we get after changing a digit is prime. For example a solution is 1033, 1733, 3733, 3739, 3779, 8779, 8179 Examples: Input : 1033 8179 Output :6 Input : 1373 8017 Output :
14 min read
D'Esopo-Pape Algorithm : Single Source Shortest Path
Given a graph and a source vertex src in a weighted undirected graph, find the shortest paths from src to all vertices in the given graph. The graph may contain negative weight edges. For this problem, we have already discussed Dijkstra's algorithm and Bellman-Ford Algorithm. But D'Esopo-Pape Algorithm performs quite well in most of the cases. Howe
11 min read
Difference between Tree edge and Back edge in graph
Tree Edge: It is an edge that is present in the tree obtained after performing DFS on the graph. All the Green edges are tree edges as shown in the below image. Back Edge: It is an edge (u, v) such that v is an ancestor of node u but not part of the DFS Traversal of the tree. Edge from 5 to 4 is a back edge. The presence of a back edge indicates a
1 min read
Shortest paths from all vertices to a destination
Given a Weighted Directed Graph and a destination vertex in the graph, find the shortest distance from all vertex to the destination vertex.Input : Output : 0 6 10 7 5Distance of 0 from 0: 0 Distance of 0 from 1: 1+5 = 6 (1->4->0) Distance of 0 from 2: 10 (2->0) Distance of 0 from 3: 1+1+5 = 7 (3->1->4->0) Distance of 0 from 4: 5
11 min read
How to find Shortest Paths from Source to all Vertices using Dijkstra's Algorithm
Given a weighted graph and a source vertex in the graph, find the shortest paths from the source to all the other vertices in the given graph. Note: The given graph does not contain any negative edge. Examples: Input: src = 0, the graph is shown below. Output: 0 4 12 19 21 11 9 8 14 Explanation: The distance from 0 to 1 = 4. The minimum distance fr
15+ min read
Program to find the shortest distance between diagonal and edge skew of a Cube
Given an integer A, denoting the length of a cube, the task is to find the shortest distance between the diagonal of a cube and an edge skew to it i.e. KL in the below figure. Examples : Input: A = 2Output: 1.4142Explanation:Length of KL = A / ?2Length of KL = 2 / 1.41 = 1.4142 Input: A = 3Output: 2.1213 Approach: The idea to solve the problem is b
4 min read
Shortest distance between two nodes in Graph by reducing weight of an edge by half
Given a weighted undirected graph consisting of N nodes and M edges, the task is to find the shortest distance between two nodes A and B by reducing the weight of one edge by half. Examples: Input: A = 0, B = 2, Below is the graph Output: 8Explanation:After reducing the weight of the edge connecting 1 and 2 by half modifies its new weight to 4. Now
11 min read
Queries to find the count of shortest paths in a Tree that contains a given edge
Given a tree with N vertices numbered from 0 to N – 1, M edges, and Q queries of the form {U, V}, such that there is a direct edge between U and V in the tree. The task for each query is to find all possible shortest paths between any possible unordered pair of vertices from the given tree which contains the edge between the given pair of nodes. Ex
8 min read
Find if there is a path between two vertices in a directed graph
Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. Example: Consider the following Graph: Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -> 2 -> 3 Input : (u, v) = (3, 6) Output: No Explanation: There is no path from 3 to 6 Approach: Either Bread
15 min read
Find if there is a path between two vertices in a directed graph | Set 2
Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. Example: Consider the following Graph: Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -> 2 -> 3 Input : (u, v) = (3, 6) Output: No Explanation: There is no path from 3 to 6 A BFS or DFS based sol
7 min read
Number of pairs such that path between pairs has the two vertices A and B
Given an undirected connected graph and two vertices A and B, the task is to find the number of pairs of vertices {X, Y} such that any path from X to Y contains both vertices A and B.Note: { X, Y } is treated equivalent to { Y, X }.X != A, X != B, Y != A and Y != B. Examples: For the above graph: Input: A = 3, B = 5 Output:4 Explanation: There are
15 min read
Find if there is a path between two vertices in an undirected graph
Given an undirected graph with N vertices and E edges and two vertices (U, V) from the graph, the task is to detect if a path exists between these two vertices. Print "Yes" if a path exists and "No" otherwise. Examples: U = 1, V = 2 Output: No Explanation: There is no edge between the two points and hence its not possible to reach 2 from 1. Input:
15+ min read
Longest path between any pair of vertices
We are given a map of cities connected with each other via cable lines such that there is no cycle between any two cities. We need to find the maximum length of cable between any two cities for given city map. Input : n = 6 1 2 3 // Cable length from 1 to 2 (or 2 to 1) is 3 2 3 4 2 6 2 6 4 6 6 5 5 Output: maximum length of cable = 12 Method 1 (Simp
12 min read
Maximize the sum of products of the degrees between any two vertices of the tree
Given an integer N, the task is to construct a tree such that the sum of [Tex]degree(u) * degree(v) [/Tex]for all ordered pairs (u, v) is the maximum where u != v. Print the maximum possible sum. Examples: Input: N = 4 Output: 26 1 / 2 / 3 / 4 For node 1, 1*2 + 1*2 + 1*1 = 5 For node 2, 2*1 + 2*2 + 2*1 = 8 For node 3, 2*1 + 2*2 + 2*1 = 8 For node 4
6 min read
three90RightbarBannerImg