0

Below is a solution Network delay problem of leetcode. I have written a all test case success solution. But not able to analyse the time complexity. I believe its O(V^2 + E) where V is the number of nodes and E edges. In this solution though I am adding all adjacents of each node every time, but not processing them further if there exists a min distance for that node already. Leetcode question link https://leetcode.com/problems/network-delay-time

   public int networkDelayTime(int[][] times, int n, int k) {
        int[] distances = new int[n+1];
        Arrays.fill(distances , -1);
        if(n > 0){
            List<List<int[]>> edges = new ArrayList<List<int[]>>();
            for(int i = 0 ; i <= n ; i++){
                edges.add(new ArrayList<int[]>());
            }
            
            for(int[] time : times){
                edges.get(time[0]).add(new int[]{time[1] , time[2]});
            }
            Queue<Vertex> queue = new LinkedList<>();
            queue.add(new Vertex(k , 0));
            while(!queue.isEmpty()){
                Vertex cx = queue.poll();
                int index = cx.index;
                int distance = cx.distance;
                //process adjacents only if distance is updated
                if(distances[index] == -1 || distances[index] > distance){ 
                    distances[index] = distance;
                    List<int[]> adjacents = edges.get(index);
                    for(int[] adjacent : adjacents){
                        queue.add(new Vertex(adjacent[0] , adjacent[1]+distance));
                    }
                }

            }
        }
        int sum = 0;
        for(int i = 1 ; i <= n; i++){
            int distance = distances[i];
            
            if(distance == -1){
                return -1;
            }
            sum =  Math.max(sum , distance);
        }
        return sum;
    }
    
    public static class Vertex{
        int index;
        int distance;
        public Vertex(int i , int d){
            index = i;
            distance = d;
        }
    }
puneet_0303
  • 197
  • 1
  • 11

1 Answers1

0

You should use PriorityQueue instead of LinkedList

pg26
  • 54
  • 3