20ms Java DFS toposort with Tarjan's algorithm


  • 0
    Y

    Note: it is a vanilla DFS toposort. I think a hash map maybe used to speed up the DFS, making it O(1) to find an edge.

    public class Solution {
        public boolean canFinish(int numCourses, int[][] prerequisites) {
            // 0 for white, unvisited
            // 1 for grey, in stack
            // 2 for black, fully explored
            int[] status = new int[numCourses];
            for (int i = 0; i < numCourses; i++) {
                if (status[i] == 0) {
                    if (!DFS(i, prerequisites, status)) {
                        return false;
                    }
                }
            }
            return true;
        }
        
        private boolean DFS(int curr, int[][] prerequisites, int[] status) {
            if (status[curr] == 1) {
                return false;
            }
            status[curr] = 1;
            for (int[] p : prerequisites) {
                if (p[0] == curr && status[p[1]] != 2) {
                    if (!DFS(p[1], prerequisites, status)) {
                        return false;
                    }
                }
            }
            status[curr] = 2;
            return true;
        }
    }

Log in to reply
 

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