如何檢測圖中的環?

Tech In Pieces發表於2020-11-27

從每個節點出發 判斷從這個節點出發DFS 最後是不是又經過了這個節點(visited)

以LC207 Course Schedule為例

HashMap<Integer, List<Integer>> courseDict = new HashMap<>();
boolean[] visited = new boolean[numCourses];
for (int i = 0; i < numCourses; i++) { //pay attention, this i stands for current course
            if (isCyclic(i, courseDict, visited)) { //starting from course i, check in this map: courseDict, and maintain a visited map
                return false;
            }
        }
        return true;

private boolean isCyclic(Integer currentCourse, HashMap<Integer, List<Integer>> courseDict, boolean[] visited) { //use backtracking to jusge if there is a cycle or not, backtracking is dfs actually
        if (visited[currentCourse]) { //path[] is actually visisted[]
            return true;
        }
        if (!courseDict.containsKey(currentCourse)) { //if current couses never have any prerequsite, then we reached the start point, then this is defintiely not a cycle
            return false;
        }
        //before backtracking, mark the node in the path
        visited[currentCourse] = true; 
        boolean ret = false;
        for (Integer nextCourse: courseDict.get(currentCourse)) { //for all of its neighbors, is anyone of them is part of the cycle, then break;
            ret = isCyclic(nextCourse, courseDict, visited);
            if (ret) { //if ret is a cycle, just break
                break;
            }
        }
        // after backtracking, remove the node from the path
        visited[currentCourse] = false; 
        return ret; //not understand this.
    }

//因為本題就是用數字表示的節點 因此這麼些還算是簡單的,詳細的總結一下
就是對圖中所有的節點進行isCycle的check
然後DFS進行check,在這個過程中需要用到:
currentNode, graphMap, visited來進行控制。注意遞迴結束的條件和backtracking對visited陣列的維護

相關文章