1 year ago

#358722

test-img

Bogdan

DFS like algorithm to find single source shortest path

I know DFS is not good choice to find shortest path from a source and BFS or dynamic programming solutions are better but i'm just interested in hypothetical situation of speed of particular algorithm.Let's say i have an undirected graph that looks just like 2-D array and i can move up, down left right on it and I choose cell in that array a[i][j] and start performing recursive algorithm like this below..

public static void dfs(int graph[][], int i, int j, int distance){
    //up right down left directions
    int dirs[][] = new int[][]{{-1, 0},{0, 1},{1, 0},{0, -1}};
    for(int dir[] : dirs){
         int new_i = i + dir[0];
         int new_j = j + dir[1];
         //out of bounds check
         if(new_i < 0 || new_i >= graph.length || new_j < 0 || new_j >= graph[0].length)
               continue;
         //if distance is less then previously found then change it and go deeper
         if(distance < graph[new_i][new_j]){
             graph[new_i][new_j] = distance;
             dfs(graph, new_i, new_j, distance + 1);
         }
    }
}

So let's say that graph array elements are filled with Integer.MAX_VALUE. And i choose particular g[i][j] set it to zero and perform dfs(g, i, j, 1). Since it's not normal dfs algorithm because it has potential to visit the same node multiple times and changes the distance to shorter one so i don't know the worst time complexity. Intuition tells me that it is slow but I have no idea what would be the worst complexity of this?

java

algorithm

depth-first-search

shortest-path

0 Answers

Your Answer

Accepted video resources