从每个节点出发 判断从这个节点出发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数组的维护