如何检测图中的环?

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值