Fork me on GitHub

15. 图-BFS

正文

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
import java.util.*

class Graph {
private val adjacencyList: MutableMap<Int, MutableList<Int>> = HashMap()

fun addEdge(src: Int, dest: Int) {
adjacencyList.computeIfAbsent(src) { mutableListOf() }.add(dest)
adjacencyList.computeIfAbsent(dest) { mutableListOf() }
}

fun bfs(startVertex: Int) {
val visited = BooleanArray(adjacencyList.size)
val queue: Queue<Int> = LinkedList()

visited[startVertex] = true
queue.offer(startVertex)

while (!queue.isEmpty()) {
val currentVertex = queue.poll()
print("$currentVertex ")

val neighbors = adjacencyList[currentVertex]
if (neighbors != null) {
for (neighbor in neighbors) {
if (!visited[neighbor]) {
visited[neighbor] = true
queue.offer(neighbor)
}
}
}
}
}
}

fun main() {
val graph = Graph()
graph.addEdge(0, 1)
graph.addEdge(0, 2)
graph.addEdge(1, 2)
graph.addEdge(2, 0)
graph.addEdge(2, 3)
graph.addEdge(3, 3)

println("BFS traversal starting from vertex 2:")
graph.bfs(2)
}
,