forked from NachtZ/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path207. Course Schedule.go
More file actions
122 lines (116 loc) · 2.01 KB
/
Copy path207. Course Schedule.go
File metadata and controls
122 lines (116 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"fmt"
"strings"
"strconv"
"math"
)
/***************************************/
//some common data struct and function using in leetcode.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
type ListNode struct {
Val int
Next *ListNode
}
type Point struct {
X int
Y int
}
func useLib(){
fmt.Println(strconv.Itoa(1))
fmt.Println(strings.Compare("1","2"))
fmt.Println(math.Abs(1.0))
}
func buildTree(nums []int) *TreeNode {
if len(nums) == 0 {
return nil
}
root := new(TreeNode)
root.Val = nums[0]
ch := make(chan *TreeNode, len(nums))
ch <- root
nums = nums[1:]
for i := 0; i < len(nums); i++ {
tree := <-ch
if nums[i] == -1 {
tree.Left = nil
} else {
tree.Left = &TreeNode{
Val: nums[i],
}
ch <- tree.Left
}
i++
if i == len(nums) || nums[i] == -1 {
tree.Right = nil
} else {
tree.Right = &TreeNode{
Val: nums[i],
}
ch <- tree.Right
}
}
return root
}
func buildList(nums []int) *ListNode {
if len(nums) == 0 {
return nil
}
root := &ListNode{
Val: nums[0],
}
tmp := root
for i := 1; i < len(nums); i++ {
tmp.Next = &ListNode{
Val: nums[i],
}
tmp = tmp.Next
}
return root
}
/**************************************************************/
func help(idx int, res []int, m map[int][]int) bool{
if res[idx] == 1{
return true
}
if res[idx] == 2{
return false
}
v,ok := m[idx]
if ok == false{
return true
}
res[idx] = 2
for i:=0;i<len(v);i++{
if help(v[i],res,m) == false{
return false
}
}
res[idx] =1
return true
}
func canFinish(numCourses int, prerequisites [][]int) bool {
m := make(map[int][]int)
res := make([]int,numCourses)//1 for can finish, 0 for unknow, 2 for is visited
for _,p := range prerequisites{//build a map
v,ok := m[p[0]]
if ok == false{
m[p[0]] = []int{p[1]}
}else{
m[p[0]] = append(v,p[1])
}
}
for i:=0;i<numCourses;i++{
if help(i,res,m)== false{
return false
}
}
return true
}
func main() {
fmt.Println(canFinish(2,[][]int{[]int{1,0},[]int{0,1}}))
}