• + 0 comments

    I try very hard, buts for now I dont know whats is wrong with my code, can somebody help please?

    class Result {

    private static class Graph {
    
         private final int size;
    
        private long nodes = 0;
    
        private final long costForRoad;
    
        private final long costForLibrary;
    
        private final int[][] cities;
    
        public Graph(int size, final long costForRoad, final long costForLibrary) {
            this.size = size;
            this.costForRoad = costForRoad;
            this.costForLibrary = costForLibrary;
            this.cities = new int[size][];
            for (int i = 0; i < size; i++) {
                this.cities[i] = new int[size];
            }
        }
    
        public void addEdge(
                final int origin,
                final int destiny
        ) {
            this.cities[origin-1][destiny-1] = 1;
            this.cities[destiny-1][origin-1] = 1;
        }
    
       public long calcCost() {
            long cost = 0;
            final boolean[] visited = new boolean[this.size];
            for (int i = 0; i < this.size; i++) {
                if(!visited[i]) {
                    nodes = 0;
                    this.dfs(i, visited);
                      if(nodes == 1) {
                        cost += nodes * costForLibrary;
                    } else {
                        cost += (nodes - 1) * costForRoad + costForLibrary;
                    }
                }
            }
    
            return cost;
        }
    
        private void dfs(
                final int vertex,
                final boolean[] visited
        ) {
            nodes += 1;
            visited[vertex] = true;
            for (int i = 0; i < this.cities[vertex].length; i++) {
                if(this.cities[vertex][i] == 1 && !visited[i]) {
                    dfs(i, visited);
                }
            }
        }
    }
    
    /*
     * Complete the 'roadsAndLibraries' function below.
     *
     * The function is expected to return a LONG_INTEGER.
     * The function accepts following parameters:
     *  1. INTEGER n
     *  2. INTEGER c_lib
     *  3. INTEGER c_road
     *  4. 2D_INTEGER_ARRAY cities
     */
    
    public static long roadsAndLibraries(int n, int c_lib, int c_road, List<List<Integer>> cities) {
    // Write your code here
        if(c_lib < c_road) {
            return n * c_lib;
        }
    
        final Graph graph = new Graph(n, c_road, c_lib);
        for(List<Integer> connections : cities) {
            graph.addEdge(connections.get(0), connections.get(1));
        }
        return graph.calcCost();
    }
    

    }