2

I read that shortest path using DFS is not possible on a weighted graph. I pretty much understood the reason of why we can't apply on DFS for shortest path using this example:- enter image description here

Here if we follow greedy approach then DFS can take path A-B-C and we will not get shortest path from A-C with traditional DFS algorithm.

I think that we can modify DFS slightly in this way to get shortest path.In this example, after the DFS goes through A-B-C and comes back again to A, we can check all adjacent nodes and if the distance from A to any of the adjacent node is less than the distance which was assigned previously(i.e 2<4) then we visit the node again even if the node is visited again before and continue the DFS from this node (like visiting C again). If we do this way, ofcourse the complexity will be bad but I don't think that its impossible to get shortest path using DFS. Is this the right approach?

Initially we have cost array initialized to infinity except for source vertex which is initialized to 0. dist(u,v) denotes edge weight from vertex u to vertex v.

function spath(vertex u)
{
  for each(vertex v adjacent to u)
   {
      if(cost[u] + dist(u,v) < cost[v])
       {
          cost[v]=cost[u]+dist(u,v);
          parent[v]=u;
          spath(v);
       }
   }
  return;
}
Zephyr
  • 1,003
  • 3
  • 17
  • 34

1 Answers1

0

I've been thinking something similar. Of course, you'd have to mark visited nodes, so that you're not running into a cycle and recurse endlessly. However, if you forbid to visit marked vertices, you may miss the shortest path.

Consider the example below:

counter example

If DFS goes $s$, $u$, $v$, $x$, $y$ then it realizes it cannot go up to $u$ again because $u$ is already visited. It concludes that $y$ cannot reach $t$. It will eventually note that

  1. the shortest $v$-$t$-path is $(v,t)$ of length 1,
  2. the shortest $u$-$t$-path is $(u,v,t)$ of length 2, and
  3. the shortest $s$-$t$-path is $(s,u,v,t)$ of length 12.

But this is wrong since $(s,x,y,u,v,t)$ has length 5.

If you allow the DFS to explore $x$ again from $s$ (after it has already been explored before via $u$ and $v$), then you will find the correct shoftest path, but this strategy may end up exploring an exponential number of $s$-$t$-paths.

igel
  • 111
  • 3