-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSolution.go
81 lines (72 loc) · 1.58 KB
/
Solution.go
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
package Solution
func Solution(n int, edges [][]int, source int, destination int) bool {
graph := make(map[int]map[int]struct{})
for _, e := range edges {
if _, ok := graph[e[0]]; !ok {
graph[e[0]] = make(map[int]struct{})
}
if _, ok := graph[e[1]]; !ok {
graph[e[1]] = make(map[int]struct{})
}
graph[e[0]][e[1]] = struct{}{}
graph[e[1]][e[0]] = struct{}{}
}
visited := map[int]struct{}{}
visited[source] = struct{}{}
found := false
var dfs func(int, *bool)
dfs = func(source int, found *bool) {
if *found {
return
}
for rel := range graph[source] {
if _, ok := visited[rel]; ok {
continue
}
if rel == destination {
*found = true
return
}
visited[rel] = struct{}{}
dfs(rel, found)
delete(visited, rel)
}
}
dfs(source, &found)
return found
}
func Solution1(n int, edges [][]int, source int, destination int) bool {
if source == destination {
return true
}
graph := make(map[int]map[int]struct{})
for _, e := range edges {
if _, ok := graph[e[0]]; !ok {
graph[e[0]] = make(map[int]struct{})
}
if _, ok := graph[e[1]]; !ok {
graph[e[1]] = make(map[int]struct{})
}
graph[e[0]][e[1]] = struct{}{}
graph[e[1]][e[0]] = struct{}{}
}
queue := []int{source}
visited := map[int]struct{}{}
visited[source] = struct{}{}
for len(queue) > 0 {
nq := make([]int, 0)
for _, item := range queue {
for rel := range graph[item] {
if rel == destination {
return true
}
if _, ok := visited[rel]; !ok {
visited[rel] = struct{}{}
nq = append(nq, rel)
}
}
}
queue = nq
}
return false
}