• + 0 comments

    Java solution using Dijkstra's algo

    class Result {
    
        /*
         * Complete the 'getCost' function below.
         * The function accepts a weighted graph defined by:
         * 1. gNodes: Number of nodes
         * 2. gFrom, gTo: Lists of nodes defining edges
         * 3. gWeight: Weights of the edges
         */
    
        // Edge class to store destination and weight
        static class Edge {
            int dest, weight;
            public Edge(int dest, int weight) {
                this.dest = dest;
                this.weight = weight;
            }
        }
    
        // State class for priority queue (Dijkstra's)
        static class State {
            int node, cost;
            public State(int node, int cost) {
                this.node = node;
                this.cost = cost;
            }
        }
    
        public static void getCost(int gNodes, List<Integer> gFrom, List<Integer> gTo, List<Integer> gWeight) {
            // Step 1: Build the graph using adjacency list
            List<List<Edge>> graph = new ArrayList<>();
            for (int i = 0; i <= gNodes; i++) {
                graph.add(new ArrayList<>());
            }
    
            for (int i = 0; i < gFrom.size(); i++) {
                int u = gFrom.get(i);
                int v = gTo.get(i);
                int weight = gWeight.get(i);
    
                graph.get(u).add(new Edge(v, weight));
                graph.get(v).add(new Edge(u, weight));
            }
    
            // Step 2: Implement Dijkstra's algorithm to find the minimum "maximum edge weight"
            PriorityQueue<State> pq = new PriorityQueue<>(Comparator.comparingInt(s -> s.cost));
            boolean[] visited = new boolean[gNodes + 1];
            int[] minCosts = new int[gNodes + 1];
            Arrays.fill(minCosts, Integer.MAX_VALUE);
            minCosts[1] = 0; // Start from node 1
            pq.offer(new State(1, 0));
    
            while (!pq.isEmpty()) {
                State current = pq.poll();
    
                // Skip already visited nodes
                if (visited[current.node]) continue;
                visited[current.node] = true;
    
                // Explore neighbors
                for (Edge edge : graph.get(current.node)) {
                    int maxCost = Math.max(current.cost, edge.weight); // Update the max edge cost along the path
                    if (maxCost < minCosts[edge.dest]) {
                        minCosts[edge.dest] = maxCost;
                        pq.offer(new State(edge.dest, maxCost));
                    }
                }
            }
    
            // Step 3: Print the result
            if (minCosts[gNodes] == Integer.MAX_VALUE) {
                System.out.println("NO PATH EXISTS");
            } else {
                System.out.println(minCosts[gNodes]);
            }
        }
    }