Skip to content

Commit 78c720a

Browse files
authored
[KTLN-666] Add Samples (#849)
* [KTLN-666] Add Samples * [KTLN-666] Add Samples
1 parent fa3fe3d commit 78c720a

File tree

2 files changed

+50
-0
lines changed
  • core-kotlin-modules/core-kotlin-10/src

2 files changed

+50
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baeldung.bfs
2+
3+
fun bfs(graph: Map<Int, List<Int>>, start: Int): List<Int> {
4+
val visited = mutableListOf<Int>()
5+
val queue = ArrayDeque<Int>()
6+
queue.add(start)
7+
while (queue.isNotEmpty()) {
8+
val vertex = queue.removeFirst()
9+
if (vertex !in visited) {
10+
visited.add(vertex)
11+
graph[vertex]?.let { neighbors -> queue.addAll(neighbors.filterNot { it in visited }) }
12+
}
13+
}
14+
return visited
15+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.baeldung.bfs
2+
3+
import org.assertj.core.api.Assertions.assertThat
4+
import org.junit.jupiter.api.Test
5+
6+
class BfsUnitTest {
7+
@Test
8+
fun `test BFS traversal order`() {
9+
val graph = mapOf(
10+
1 to listOf(2, 3, 4),
11+
2 to listOf(5, 6),
12+
3 to listOf(),
13+
4 to listOf(7, 8),
14+
5 to listOf(),
15+
6 to listOf(),
16+
7 to listOf(),
17+
8 to listOf()
18+
)
19+
20+
val traversalOrder = bfs(graph, 1)
21+
22+
23+
// Level 1
24+
val levelOne = listOf(traversalOrder.first())
25+
assertThat(levelOne).containsExactly(1)
26+
27+
// Level 2
28+
val levelTwo = traversalOrder.drop(1).take(3)
29+
assertThat(levelTwo).containsExactlyInAnyOrder(2, 3, 4)
30+
31+
// Level 3
32+
val levelThree = traversalOrder.drop(4)
33+
assertThat(levelThree).containsExactlyInAnyOrder(5, 6, 7, 8)
34+
}
35+
}

0 commit comments

Comments
 (0)