Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f1d3085

Browse files
Breadth first search graph traversal
1 parent 07c441d commit f1d3085

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

‎src/main/kotlin/pl/dmichalski/algorithms/data_structures/_11_graph_traversal/Runner.kt‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ object Runner {
2626
depthFirstSearch = undirectedGraph.depthFirstSearchIterative(VERTEX_A)
2727
println("Graph elements: $depthFirstSearch")
2828
printUndirectedGraph(undirectedGraph)
29+
30+
println("------------------ Breadth First Search traversal ------------------ ")
31+
undirectedGraph = getUndirectedGraph()
32+
val breadthFirstSearch = undirectedGraph.breadthFirstSearch(VERTEX_A)
33+
println("Graph elements: $breadthFirstSearch")
34+
printUndirectedGraph(undirectedGraph)
35+
36+
2937
}
3038

3139
/**

‎src/main/kotlin/pl/dmichalski/algorithms/data_structures/_11_graph_traversal/UndirectedGraph.kt‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,11 @@ class UndirectedGraph {
3939
result.add(node)
4040
node.getConnections()
4141
.map { con -> findNode(con) }
42-
.filter { neighbour -> !visited.contains(neighbour!!.getVertex()) }
43-
.forEach { neighbour -> dfs(neighbour) }
42+
.forEach { neighbour ->
43+
if (!visited.contains(neighbour?.getVertex())) {
44+
dfs(neighbour)
45+
}
46+
}
4447
}
4548

4649
dfs(node)
@@ -72,6 +75,32 @@ class UndirectedGraph {
7275
return result
7376
}
7477

78+
79+
fun breadthFirstSearch(vertex: String): MutableList<Node> {
80+
val queue = ArrayDeque<Node>()
81+
queue.push(findNode(vertex)!!)
82+
val result: MutableList<Node> = ArrayList()
83+
val visited: MutableSet<String> = HashSet()
84+
var currentVertex: Node?
85+
86+
visited.add(vertex)
87+
while (queue.size > 0) {
88+
currentVertex = queue.pop()
89+
result.add(currentVertex)
90+
91+
currentVertex.getConnections()
92+
.map { con -> findNode(con) }
93+
.filter { neighbour -> !visited.contains(neighbour!!.getVertex()) }
94+
.forEach { neighbour ->
95+
visited.add(neighbour!!.getVertex())
96+
queue.add(neighbour)
97+
}
98+
}
99+
100+
return result
101+
}
102+
103+
75104
override fun toString(): String {
76105
return "UndirectedGraph(adjacencyList='$adjacencyList')\n"
77106
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /