Please read the new rule regarding the restriction on the use of AI tools. ×

Minimum distance path with DFS in a weighted undirected graph.

Revision en1, by devnamrits, 2022-05-08 07:06:59

I need to find the minimum distance from 0th node to (n-1)th node in a weighted undirected graph. We can apply Dijkstra's Algo here. But I have a question: What if we start from the 0th node and add distances and reach the destination while backtracking and then find the minimum of distances along all the paths leading to (n-1)th node. Is this hypothesis correct??

I want help regarding this question from leetcode: Number of ways to arrive at destination

I have done something like this:

class Solution {
public:
    map<pair<int,int>,int> edge;
    int target;
    long long mnTime;
    long long ans = 0;
    const int mod = 1e9+7;
    
    long long returnMinTime(int n, vector<int> adj[], vector<bool> &vis,int par){
        if(n==target){
            return 0;
        }
        vis[n] = 1;
        long long val;
        long long tmp = INT_MAX;
        for(auto i:adj[n]){
            if(vis[i]==0){
                val = edge[{n,i}] + returnMinTime(i,adj,vis,n);
                tmp = min(val,tmp);
            }
        }
        return tmp;
    }

    int numberOfWays(int n,vector<int> adj[],vector<bool> &vis,int par,int time){
        
        if(time==0 && n==target){
            return 1;
        }
        if(time<=0)
            return 0;
        vis[n] = 1;
        int val = 0;
        for(auto i:adj[n]){
            if(!vis[i]){
                val += numberOfWays(i,adj,vis,n,time-edge[{n,i}])%mod;
            }
        }
        vis[n] = 0;
        return val%mod;
    }
    
    int countPaths(int n, vector<vector<int>>& roads) {
        vector<int> adj[n];
        vector<bool> vis(n,0);
        target = n-1;
        for(auto i:roads){
            adj[i[0]].push_back(i[1]);
            adj[i[1]].push_back(i[0]);
            edge[{i[0],i[1]}] = i[2];
            edge[{i[1],i[0]}] = i[2];
        }
        mnTime = returnMinTime(0,adj,vis,-1);
        fill(vis.begin(),vis.end(),0);
        return numberOfWays(0,adj,vis,-1,mnTime);
        return ans;
    }
};

It has passed some of the testcases but not all. Your help will be appreciated.

Tags dfs and similar, shortest path, leetcode

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English devnamrits 2022-05-08 07:06:59 2301 Initial revision (published)