DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Number of Restricted Paths From First to Last Node

Problem

class Solution {
    public int countRestrictedPaths(int n, int[][] edges) {

        List<List<Pair>> adj = new ArrayList<>();
        for(int i= 0;i<n;i++){
            adj.add(new ArrayList<>());
        }
        for(int edge[] : edges){
            int i = edge[0]-1;
            int j = edge[1]-1;
            int w = edge[2];
            adj.get(i).add(new Pair(j,w));
            adj.get(j).add(new Pair(i,w));
        }
        int distance[] = new int[n];
        Arrays.fill(distance,Integer.MAX_VALUE);
        Queue<Pair> q  = new PriorityQueue<>((a,b)-> Integer.compare(a.c, b.c));
        distance[n-1] = 0;
        // dijsktras with last node as source, this way we will have shortest distance to reach to this node from all the other nodes ( because this will compute shortest distance from last node to all the other node hence vice versa is also true)
        q.add(new Pair(n-1, 0));
        while(!q.isEmpty()){
            Pair p = q.remove();
            int node = p.j;
            int cost = p.c;
            if(cost> distance[node]) continue; //additional optimization (code works without this though)
            for(Pair adjPair : adj.get(node)){
                int adjNode = adjPair.j;
                int w = adjPair.c;
                if(distance[adjNode]> cost + w){
                    distance[adjNode] = cost + w;
                    q.add(new Pair(adjNode, distance[adjNode]));
                }
            }
        }
        int dp[] = new int[n];
        Arrays.fill(dp,-1);
        int restrictedPath = dfs(0,distance,adj, n-1, dp);
        return restrictedPath;
    }
    public int dfs(int i,int[] distance, List<List<Pair>> adj, int lastNode, int dp[]){
        if(i == lastNode) return 1;
        if(dp[i]!=-1) return dp[i];
        int count =0;
        for(Pair adjPair: adj.get(i)){
            int j = adjPair.j;
            if(distance[i]<=distance[j]) continue;
            count+=dfs(j, distance, adj,lastNode, dp);
            count= (count) %((int)1e9 + 7);
        }
        return dp[i] = count;
    }
}
class Pair{
    int j;
    int c;
    public Pair(int j ,int c){
        this.j = j;
        this.c = c;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)