forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjdalma.kt
94 lines (78 loc) Β· 2.39 KB
/
jdalma.kt
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
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import java.lang.RuntimeException
import java.util.ArrayDeque
import java.util.Queue
class `clone-graph` {
data class Node(var `val`: Int) {
var neighbors: ArrayList<Node?> = ArrayList()
}
fun cloneGraph(node: Node?): Node? {
if (node == null) return null
return usingBFS(node)
}
/**
* TC: O(n), SC: O(n)
*/
private fun usingDFS(node: Node): Node {
fun dfs(node: Node, nodes: MutableMap<Int, Node>): Node {
nodes[node.`val`]?.let {
return it
}
val copy = Node(node.`val`)
nodes[node.`val`] = copy
for (near in node.neighbors.filterNotNull()) {
copy.neighbors.add(dfs(near, nodes))
}
return copy
}
return dfs(node, mutableMapOf())
}
/**
* TC: O(n), SC: O(n)
*/
private fun usingBFS(node: Node): Node {
val nodes = mutableMapOf<Int, Node>().apply {
this[node.`val`] = Node(node.`val`)
}
val queue: Queue<Node> = ArrayDeque<Node>().apply {
this.offer(node)
}
while (queue.isNotEmpty()) {
val now = queue.poll()
val copy = nodes[now.`val`] ?: throw RuntimeException()
for (near in now.neighbors.filterNotNull()) {
if (!nodes.containsKey(near.`val`)) {
nodes[near.`val`] = Node(near.`val`)
queue.add(near)
}
copy.neighbors.add(nodes[near.`val`])
}
}
return nodes[node.`val`] ?: Node(node.`val`)
}
private fun fixture(): Node {
val one = Node(1)
val two = Node(2)
val three = Node(3)
val four = Node(4)
one.neighbors.add(two)
one.neighbors.add(four)
two.neighbors.add(one)
two.neighbors.add(three)
three.neighbors.add(two)
three.neighbors.add(four)
four.neighbors.add(one)
four.neighbors.add(three)
return one
}
@Test
fun `μ
λ ₯λ°μ λ
Έλμ κΉμ 볡μ¬λ³Έμ λ°ννλ€`() {
val actualNode = fixture()
val expectNode = cloneGraph(actualNode)
actualNode shouldBe expectNode
actualNode.`val` = 9999
expectNode!!.`val` shouldBe 1
}
}