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 **x _{i}** denote the distance to node 1, and

**y**denote the distance to node

_{i}**N**. Below are the steps:

- Maintain a 2D matrix(say
**dist[2][]**) having**2**rows and**N**columns. - In the first row, Maintain the shortest distance between node
**1**and other vertices in the graph using BFS Traversal. - In the second row, Maintain the shortest distance between node
**N**and the other vertices of the graph using BFS Traversal. - 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 (x
_{i}– y_{i}) 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]).

- Create a vector of pairs and store the value of (x
- 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:

## CPP

`// 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; ` `} ` |

*chevron_right*

*filter_none*

**Output:**

3

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

**Auxiliary Space:** O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Queries to find the count of shortest paths in a Tree that contains a given edge
- Maximum cost path in an Undirected Graph such that no edge is visited twice in a row
- Finding shortest path between any two nodes using Floyd Warshall Algorithm
- Maximize the median of the given array after adding K elements to the same array
- Dijkstra's shortest path algorithm | Greedy Algo-7
- Multi Source Shortest Path in Unweighted Graph
- Dijkstra's shortest path with minimum edges
- Shortest path to traverse all the elements of a circular array in increasing order
- Shortest path in a directed graph by Dijkstra’s algorithm
- Shortest Path with even number of Edges from Source to Destination
- Building an undirected graph and finding shortest path using Dictionaries in Python
- Shortest path in a complement graph
- Create a Graph by connecting divisors from N to M and find shortest path
- Applications of Dijkstra's shortest path algorithm
- Shortest Path using Meet In The Middle
- Product of minimum edge weight between all pairs of a Tree
- Check if a given Graph is 2-edge connected or not
- Minimum initial vertices to traverse whole matrix with given conditions
- Minimize cost to color all the vertices of an Undirected Graph using given operation
- Find weight of MST in a complete graph with edge-weights either 0 or 1

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.