Skip to content

Commit 825e10f

Browse files
committed
문제 추가
1 parent 5da9c09 commit 825e10f

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

clone-graph/jdalma.kt

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
import java.lang.RuntimeException
6+
import java.util.ArrayDeque
7+
import java.util.Queue
8+
9+
class `clone-graph` {
10+
11+
data class Node(var `val`: Int) {
12+
var neighbors: ArrayList<Node?> = ArrayList()
13+
}
14+
15+
fun cloneGraph(node: Node?): Node? {
16+
if (node == null) return null
17+
18+
return usingBFS(node)
19+
}
20+
21+
/**
22+
* TC: O(n), SC: O(n)
23+
*/
24+
private fun usingDFS(node: Node): Node {
25+
26+
fun dfs(node: Node, nodes: MutableMap<Int, Node>): Node {
27+
nodes[node.`val`]?.let {
28+
return it
29+
}
30+
val copy = Node(node.`val`)
31+
nodes[node.`val`] = copy
32+
33+
for (near in node.neighbors.filterNotNull()) {
34+
copy.neighbors.add(dfs(near, nodes))
35+
}
36+
37+
return copy
38+
}
39+
return dfs(node, mutableMapOf())
40+
}
41+
42+
/**
43+
* TC: O(n), SC: O(n)
44+
*/
45+
private fun usingBFS(node: Node): Node {
46+
val nodes = mutableMapOf<Int, Node>().apply {
47+
this[node.`val`] = Node(node.`val`)
48+
}
49+
val queue: Queue<Node> = ArrayDeque<Node>().apply {
50+
this.offer(node)
51+
}
52+
53+
while (queue.isNotEmpty()) {
54+
val now = queue.poll()
55+
val copy = nodes[now.`val`] ?: throw RuntimeException()
56+
for (near in now.neighbors.filterNotNull()) {
57+
if (!nodes.containsKey(near.`val`)) {
58+
nodes[near.`val`] = Node(near.`val`)
59+
queue.add(near)
60+
}
61+
copy.neighbors.add(nodes[near.`val`])
62+
}
63+
}
64+
return nodes[node.`val`] ?: Node(node.`val`)
65+
}
66+
67+
private fun fixture(): Node {
68+
val one = Node(1)
69+
val two = Node(2)
70+
val three = Node(3)
71+
val four = Node(4)
72+
73+
one.neighbors.add(two)
74+
one.neighbors.add(four)
75+
two.neighbors.add(one)
76+
two.neighbors.add(three)
77+
three.neighbors.add(two)
78+
three.neighbors.add(four)
79+
four.neighbors.add(one)
80+
four.neighbors.add(three)
81+
82+
return one
83+
}
84+
85+
@Test
86+
fun `입력받은 노드의 깊은 복사본을 반환한다`() {
87+
val actualNode = fixture()
88+
val expectNode = cloneGraph(actualNode)
89+
actualNode shouldBe expectNode
90+
91+
actualNode.`val` = 9999
92+
expectNode!!.`val` shouldBe 1
93+
}
94+
}

0 commit comments

Comments
 (0)