Why does this Java code not work?


  • 0
    L

    public class Solution {

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        
        HashMap<Integer, HashSet<Integer>> al = new HashMap<Integer, HashSet<Integer>>();
        int psize = prerequisites.length;
    
        for (int i = 0; i < psize; ++i) {
            if (!al.containsKey(prerequisites[i][1])) {
                HashSet<Integer> s = new HashSet<Integer>();
                s.add(prerequisites[i][0]);
                al.put(prerequisites[i][1], s);
            }
            else {
                al.get(prerequisites[i][1]).add(prerequisites[i][0]);
            }
        }
        
        String[] states = new String[numCourses];
        Arrays.fill(states, "unvisited");
        
        for (int i = 0; i < numCourses; ++i) {
            if (states[i].equals("unvisited")) {
                if (hasCycle(al, states, i)) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    private boolean hasCycle(HashMap<Integer, HashSet<Integer>> al, String[] states, int i) {
        states[i] = "inProgress";
        HashSet<Integer> successors = al.get(i);
        
        for (int m : successors) {
            if (states[m].equals("inProgress")) {
                return true;
            }
            else if (states[m].equals("unvisited")) {
                if (hasCycle(al, states, m)) {
                    return true;
                }
            }
        }
        
        states[i] = "done";
        return false;
    }
    

    }


  • 0
    L

    The issue was that I didn't check the null Set container before preforming the for-each loop at line 36


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.