5ms DFS beat 98% and 9ms BFS in java


  • 3
    L

    DFS:

    public class Solution {
        public boolean canFinish(int numCourses, int[][] prerequisites) {
            ArrayList<Integer>[] graph = new ArrayList[numCourses];//tricky
            for(int i = 0; i < numCourses; i++) {
                graph[i] = new ArrayList<Integer>();
            }
    
            for(int[] pre : prerequisites) {
                graph[pre[1]].add(pre[0]);
            }
    
            boolean[] visited = new boolean[numCourses],
            boolean[] finished = new boolean[numCourses];
            for(int i = 0; i < numCourses; i++) {
                if(!helper(graph, visited, finished, i)){
                    return false;
                }
            }
    
            return true;
        }
    
        public boolean helper(ArrayList[] graph, boolean[] visited, boolean[] finished, int s) {
            if(finished[s]) {
                return true;
            } else if(visited[s]) {
                return false;
            } else {
                visited[s] = true;
            }
    
            for(int i=0; i<graph[s].size();i++){
                int adj = (int)graph[s].get(i);//tricky
                if(!helper(graph, visited, finished, adj)){
                    return false;
                }
            }
    
            finished[s] = true;
            return true;
        }
    }
    

    BFS:

    public class Solution {
        public boolean canFinish(int numCourses, int[][] prerequisites) {
            List<List<Integer>> graph = new ArrayList<>();
            for(int i = 0; i < numCourses; i++) {
                graph.add(new ArrayList<>());
            }
    
            int[] indegree = new int[numCourses];
            for(int[] edge : prerequisites) {
                graph.get(edge[1]).add(edge[0]);
    
                indegree[edge[0]]++;
            }
    
            Queue<Integer> q = new LinkedList<>();
            for(int i = 0; i < numCourses; i++) {
                if(indegree[i] == 0){
                    q.offer(i);
                }
            }
    
            int count = 0;
            while(!q.isEmpty()) {
                int s = q.poll();
                for(int adj : graph.get(s)) {
                    indegree[adj]--;
                    count++;
                    if(indegree[adj] == 0) {
                        q.offer(adj);
                    }
                }
            }
    
            return count == prerequisites.length;
        }
    }
    

Log in to reply
 

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