Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Created June 2, 2022 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rommansabbir/3f98853bd285e3830bc7bb5f3a332c66 to your computer and use it in GitHub Desktop.
Save rommansabbir/3f98853bd285e3830bc7bb5f3a332c66 to your computer and use it in GitHub Desktop.
BFS Algorithm Implementation in Kotlin
object BFS {
@JvmStatic
fun main(args: Array<String>) {
val station1 = Node("Westminster", null, null)
val station2 = Node("Waterloo", station1, null)
val station3 = Node("Trafalgar Square", station1, station2)
val station4 = Node("Canary Wharf", station2, station3)
val station5 = Node("London Bridge", station4, station3)
val station6 = Node("Tottenham Court Road", station5, station4)
val bfs = BreadthFirstSearch(station6, station3)
print("Path Found:: ${bfs.compute()}")
}
}
/**
* Class that represent a node by following a UID, firstChild and secondChild.
* Provide public API to get child as a list [getChildren].
*/
class Node(val id: String, private val firstChild: Node? = null, private val secondChild: Node? = null) {
fun getChildren(): MutableList<Node> {
val list = mutableListOf<Node>()
firstChild?.let { list.add(it) }
secondChild?.let { list.add(it) }
return list
}
}
/**
* Class that represent the Breadth First Algorithm.
*
* @param startNode [Node] from where the search will start.
* @param goalNode [Node] to be found.
*/
class BreadthFirstSearch(private val startNode: Node, private val goalNode: Node) {
fun compute(): Boolean {
// Check if the start and goal is the same or not.
if (startNode.id == goalNode.id) {
return true
}
// Create a new Queue and ArrayList to hold traversed and visited nodes.
val queue: Queue<Node> = LinkedList()
val explored: ArrayList<Node> = arrayListOf()
// Add start node as the entry point and mark as visited.
queue.add(startNode)
explored.add(startNode)
// Start finding the goal node from the Queue.
while (!queue.isEmpty()) {
// First current node remove from the Queue.
val current = queue.remove()
// Check if matches or not.
if (current.id == goalNode.id) {
return true
} else {
// Check if it has child nodes or not.
// If it has, start the searching process again.
if (current.getChildren().isEmpty()) {
return false
} else {
queue.addAll(current.getChildren())
}
}
explored.add(current)
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment