4 Star 13 Fork 10

ShirDon-廖显东/零基础Go语言算法实战源码

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
interview6-2.go 1.18 KB
一键复制 编辑 原始数据 按行查看 历史
ShirDon-廖显东 提交于 2024-04-22 14:56 +08:00 . first commit
// ++++++++++++++++++++++++++++++++++++++++
// 《零基础Go语言算法实战》源码
// ++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// Gitee:https://gitee.com/shirdonl/goAlgorithms.git
// Buy link :https://item.jd.com/14101229.html
// ++++++++++++++++++++++++++++++++++++++++
package main
import "fmt"
func canFinishCourses(numCourses int, array [][]int) bool {
graph := map[int][]int{}
for _, pre := range array {
graph[pre[0]] = append(graph[pre[0]], pre[1])
}
traced := map[int]bool{}
visited := map[int]bool{}
for i := 0; i < numCourses; i++ {
if hasCycle(i, graph, traced, visited) {
return false
}
}
return true
}
func hasCycle(course int, graph map[int][]int, traced, visited map[int]bool) bool {
if traced[course] {
return true
}
if visited[course] {
return false
}
traced[course] = true
for _, pre := range graph[course] {
if hasCycle(pre, graph, traced, visited) {
return true
}
}
traced[course] = false
visited[course] = true
return false
}
func main() {
array := [][]int{{1, 2}, {0, 2}}
res := canFinishCourses(2, array)
fmt.Println(res)
}
//$ go run interview5-2.go
//true
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/shirdonl/goAlgorithms.git
git@gitee.com:shirdonl/goAlgorithms.git
shirdonl
goAlgorithms
零基础Go语言算法实战源码
3e77a12194dd

搜索帮助