32ms Java DFS toposort with Tarjan's algorithm


  • 0
    Y
    public class Solution {
        public int[] findOrder(int numCourses, int[][] prerequisites) {
            // 0 for white, unvisited
            // 1 for grey, in stack
            // 2 for black, fully explored
            List<Integer> result = new ArrayList<Integer>();
            int[] status = new int[numCourses];
            for (int i = 0; i < numCourses; i++) {
                if (status[i] == 0) {
                    DFS(i, prerequisites, status, result);
                }
            }
            if (result.size() != numCourses) {
                return new int[0];
            }
            int[] finalResult = new int[result.size()];
            for (int i = 0; i < result.size(); i++) {
                finalResult[i] = result.get(i);
            }
            return finalResult;
        }
        
        private boolean DFS(int curr, int[][] prerequisites, int[] status, List<Integer> result) {
            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, result)) {
                        return false;
                    }
                }
            }
            status[curr] = 2;
            result.add(curr);
            return true;
        }
    }

Log in to reply
 

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