File tree Expand file tree Collapse file tree 2 files changed +50
-0
lines changed
core-kotlin-modules/core-kotlin-10/src
main/kotlin/com/baeldung/bfs
test/kotlin/com/baeldung/bfs Expand file tree Collapse file tree 2 files changed +50
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments