Course Schedule I&II

Course Schedule

這題的本質就是,給你一個代表 graph 的 adjacency array,判斷 graph 是否有環。其實和 Graph Valid Tree 非常像。

DFS 找環性能優異,DFS找環相當於在DFS的基礎上(1)需要傳一個visited數組,每次訪問某個點的時候判斷該點的visit數值,如果爲0表示沒有被訪問過,1表示有環,2表示訪問完成。再次訪問1肯定有環。

(2)每次傳一個cur參數,表明你現在正在遍歷哪個點。
(2)加上一個boolean返回值的helper函數,當遇見環的時候直接返回。
(3)找環屬於preorder。
public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        ArrayList[] graph = new ArrayList[numCourses];
        int[] visited = new int[numCourses];


        for(int i = 0; i < numCourses; i++){
            graph[i] = new ArrayList<Integer>();
        }


        for(int[] num : prerequisites){
            int parent = num[1];
            int child = num[0];
            graph[parent].add(child);
        }


        for(int i = 0; i < numCourses; i++){
            if(visited[i] == 0 && hasCycle(i, visited, graph)) return false;
        }


        return true;
    }


    private boolean hasCycle(int cur, int[] visited, ArrayList[] graph){
        visited[cur] = 1;


        boolean hasCycle = false;


        for(int i = 0; i < graph[cur].size(); i++){
            int next = (int) graph[cur].get(i);
            if(visited[next] == 1) return true;
            else if(visited[next] == 0){
                hasCycle = hasCycle || hasCycle(next, visited, graph);
            }
        }


        visited[cur] = 2;


        return hasCycle;
    }
}

BFS 寫法,速度超過 82.34%

思路上承接了原來的 topological sort BFS 解法

(1) 建 array 保存所有節點的 indegree

(2) 用ArrayList[]存儲graph

在 BFS 時只有 indegree = 0 時纔會被加入隊列,如果 graph 中有環,會出現有環的部分永遠無法進入 BFS 被訪問的情況,因此在結尾我們只需要看一下到底有沒有點從來沒被訪問過即可(設置一個counter,看counter ?= number of nodes


Course Schedule II

超過 80.69%,速度尚可~

思路和上一題完全一樣,只不過留了個 index 用於記錄拓撲順序。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章