# how to identify the second shortest path in an unweighted undirected graph

Given an unweighted and undirected graph, can I identify the second best shortest path from every node to every other node in polynomial time? When I say the second best, as long as one edge is different than the edges existing in the first shortest path, it is acceptable. This also implies that the length of the paths can be equal.

If so, what is the algorithm that I should use?

• Find the shortest, then delete the path and run the algorithm on the smaller graph. – David G. Stork Aug 29 at 19:15
• @DavidG.Stork what do you mean by deleting the path? What if the second shortest path could contain an edge existing in that path? For instance, say the shortest path from node 1 to node 4 is (1-2-3-4). If there is another path as (1-2-5-4), and if I delete the first path, then how can the algorithm identify the second shortest path? – whitepanda Aug 29 at 19:19
• – Math1000 Aug 29 at 19:36
• @Math1000 That answer is given for the weighted graphs. I believe there should be something faster in my case that will return the solution in seconds( hopefully). Please consider that I might have thousands of nodes. So I need the most efficient way to do this. – whitepanda Aug 29 at 19:44
• @whitepanda: I'm not sure this is optimal, but I would delete the first segment of the shortest path and then run the algorithm. Then I would replace that segment and delete the second segment, and then run the algorithm. Then replace that segment and delete the third, ... and so forth. This forces the second shortest to differ by at least one segment from the global shortest path. – David G. Stork Aug 29 at 20:25

A naive way that would work is the following: Let $$P$$ be a shortest path from $$u$$ to $$v$$. For each $$e \in P$$ find the shortest path $$P_{e}$$ in $$G \setminus \{e\}$$. Then the shortest of the $$P_{e}$$s, $$e \in P$$, is a second shortest path from $$u$$ to $$v$$.
• It will run in polynomial time: $n^2$ paths $P$ each w at most $n$ edges so $n^3$ BFSs. There may be a faster way to do it than this though. – Mike Aug 29 at 19:52