Advertisement
amitsen01ei

FindingGoodNodes.java

Oct 30th, 2023 (edited)
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | Source Code | 0 0
  1. public class Solution {
  2.    
  3.     private Map<Integer, List<Integer>> graph;
  4.     private List<Integer> a;
  5.     private int c;
  6.  
  7.     private int dfs(int node, int goodCount) {
  8.         if (this.a.get(node - 1) == 1) {
  9.             goodCount++;
  10.         }
  11.  
  12.         if (goodCount > this.c) {
  13.             return 0;
  14.         }
  15.  
  16.         if (this.graph.get(node).isEmpty() && node != 1) {
  17.             return 1;
  18.         }
  19.  
  20.         var pathCount = 0;
  21.         List<Integer> neighbors = new ArrayList<>(this.graph.get(node));
  22.        
  23.         for (var neighbor : neighbors) {
  24.             this.graph.get(neighbor).remove((Integer) node);
  25.             pathCount += dfs(neighbor, goodCount);
  26.         }
  27.         return pathCount;
  28.     }
  29.    
  30.     /**
  31.      * This method counts the number of root to leaf paths in a tree
  32.      * that contain not more than a given number of good nodes.
  33.      * <p>
  34.      * Time Complexity: O(N) - where N is the number of nodes in the tree.
  35.      * Every node and edge is visited once.
  36.      * <p>
  37.      * Space Complexity: O(N) - for storing the graph and the recursion call stack.
  38.      *
  39.      * @param a Binary List representing good (1) and bad (0) nodes.
  40.      * @param b List of List of Integer representing edges of the tree.
  41.      * @param c Maximum number of good nodes allowed in a root to leaf path.
  42.      */
  43.     public int solve(List<Integer> a, List<List<Integer>> b, int c) {
  44.        
  45.         this.a = a;
  46.         this.c = c;
  47.         this.graph = new HashMap<>();
  48.  
  49.         for (var i = 0; i < a.size(); i++) {
  50.             this.graph.put(i + 1, new ArrayList<>());
  51.         }
  52.  
  53.         for (var edge : b) {
  54.             this.graph.get(edge.get(0)).add(edge.get(1));
  55.             this.graph.get(edge.get(1)).add(edge.get(0));
  56.         }
  57.  
  58.         return dfs(1, 0);
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement