forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobzva.go
More file actions
57 lines (55 loc) ยท 1.88 KB
/
obzva.go
File metadata and controls
57 lines (55 loc) ยท 1.88 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
/*
ํ์ด
- valid tree์ธ์ง ํ๋ณํ๋ ๋ฌธ์ ์
๋๋ค
์ฃผ์ด์ง input์ด valid tree์ด๋ ค๋ฉด,
1. cycle์ด ์์ด์ผ ํฉ๋๋ค (cycle์ด ์๋ ๊ฒฝ์ฐ: [[0, 1], [1, 2], [2, 0]])
2. ๋ชจ๋ node๊ฐ ์ฐ๊ฒฐ๋์ด ์์ด์ผ ํฉ๋๋ค (๋ชจ๋ node๊ฐ ์ฐ๊ฒฐ๋์ง ์์ ๊ฒฝ์ฐ: [[0, 1], [2, 3]])
- dfs ๋ฐฉ์์ ํจ์๋ฅผ ์ฌ๊ท ํธ์ถํ์ฌ ํ์ดํ ์ ์์ต๋๋ค
Big O
- N: n
- E: ์ฃผ์ด์ง ๋ฐฐ์ด edges์ ํฌ๊ธฐ
- Time complexity: O(N)
- ๋ชจ๋ node๋ฅผ ์ต๋ 1๋ฒ์ฉ ํ์ํฉ๋๋ค
- Space complexity: O(E + N)
- visited์ ํฌ๊ธฐ๋ N์ ๋น๋กํ์ฌ ์ฆ๊ฐํฉ๋๋ค -> O(N)
- adj์ ํฌ๊ธฐ๋ E์ ๋น๋กํ์ฌ ์ฆ๊ฐํฉ๋๋ค -> O(E)
- dfs์ ์ฌ๊ทํธ์ถ ์คํ ๊น์ด๋ ์ต์
์ ๊ฒฝ์ฐ N๊น์ง ์ปค์ง ์ ์์ต๋๋ค -> O(N)
*/
func validTree(n int, edges [][]int) bool {
// valid tree๋ n-1๊ฐ์ edge๋ฅผ ๊ฐ์ง ์ ๋ฐ์ ์์ตvalidTree
// ์๋ ํ๋ณ์์ ์ด์ฉํ๋ฉด ์ ํจํ์ง ์์ input์ ๋ํด ์๋นํ ์ฐ์ฐ์ ์ค์ผ ์ ์์ต๋๋ค
if len(edges) != n-1 {
return false
}
// ์ฃผ์ด์ง 2์ฐจ์ ๋ฐฐ์ด edges๋ฅผ ์ด์ฉํด adjacency list๋ฅผ ์์ฑํฉ๋๋ค
adj := make([][]int, n)
for _, edge := range edges {
adj[edge[0]] = append(adj[edge[0]], edge[1])
adj[edge[1]] = append(adj[edge[1]], edge[0])
}
// cycle์ด ์๋์ง ์ฌ๋ถ๋ฅผ ํ๋จํ๊ธฐ ์ํด visited๋ผ๋ map์ ์์ฑํฉ๋๋ค (Go์์๋ map์ผ๋ก set ๊ธฐ๋ฅ์ ๋์ ํจ)
visited := make(map[int]bool)
var dfs func(int, int) bool
dfs = func(node int, parent int) bool {
// cycle ๋ฐ๊ฒฌ์ false return
if _, ok := visited[node]; ok {
return false
}
visited[node] = true
for _, next := range adj[node] {
if next == parent {
continue
}
if !dfs(next, node) {
return false
}
}
return true
}
// cycle ์ฌ๋ถ๋ฅผ ํ๋จํฉ๋๋ค
if !dfs(0, -1) {
return false
}
// node๊ฐ ๋ชจ๋ ์ฐ๊ฒฐ๋์ด ์๋์ง ์ฌ๋ถ๋ฅผ ํ๋จํฉ๋๋ค
return len(visited) == n
}