 ## Introduction #

This tutorial is part of a collection tutorials on basic data structures and algorithms that are created using Kotlin. This project is useful if you are trying to get more fluency in Kotlin or need a refresher to do interview prep for software engineering roles.

### How to run this project #

You can get the code for this and all the other tutorials in this collection from this github repo. Here’s a screen capture of project in this repo in action. Once you’ve cloned the repo, type `./gradlew run` in order to build and run this project from the command line.

## Undirected graphs #

Here’s code in Kotlin that describes undirected graphs with an adjacency list to represent the edges. For more info, check out this website.

• The adjacency list is stored in a `HashMap`, which holds a `HashSet` of nodes.

• We use a `HashSet` instead of `LinkedHashSet` because the order of insertion doesn’t really matter. This is also why we don’t use `TreeSet`, since the edges don’t need to be sorted.

• A node / vertex in this graph can be of any class (`T`).

Here’s an image of an undirected graph. ``````/**
*/
class Graph<T> {
val adjacencyMap: HashMap<T, HashSet<T>> = HashMap()

fun addEdge(sourceVertex: T, destinationVertex: T) {
// Add edge to source vertex / node.
.computeIfAbsent(sourceVertex) { HashSet() }
// Add edge to destination vertex / node.
.computeIfAbsent(destinationVertex) { HashSet() }
}

override fun toString(): String = StringBuffer().apply {
append("\$key -> ")
}
}.toString()
}
``````

### DFS #

To do a depth first traversal of the graph, here’s some code that uses a Stack (LIFO).

``````/**
* Depth first traversal leverages a [Stack] (LIFO).
*
* It's possible to use recursion instead of using this iterative
* implementation using a [Stack].
* Also, this algorithm is almost the same as [breadthFirstTraversal],
* except that [Stack] (LIFO) is replaced w/ a [Queue] (FIFO).
*
*/
fun <T> depthFirstTraversal(graph: Graph<T>, startNode: T): String {
// Mark all the vertices / nodes as not visited.
val visited = mutableSetOf<T>()

// Create a stack for DFS. Both ArrayDeque and LinkedList implement Deque.
val stack: Deque<T> = ArrayDeque()

// Initial step -> add the startNode to the stack.
stack.push(startNode)

// Store the sequence in which nodes are visited, for return value.
val traversalList = mutableListOf<T>()

// Traverse the graph.
while (stack.isNotEmpty()) {
// Pop the node off the top of the stack.
val currentNode = stack.pop()

if (!visited.contains(currentNode)) {

// Store this for the result.

// Mark the current node visited and add to the traversal list.

stack.push(node)
}

}

}

return traversalList.joinToString()
}
``````

### BFS #

To do a breadth first traversal of the graph, here’s some code that uses a Queue (FIFO). The following implementation doesn’t use recursion, and also keeps track of the depth as it’s traversing the graph. We also have to keep track of which nodes are visited and unvisited, so that we don’t backtrack and revisit node that have already been visited. The `depthMap` is optional as it is used to track the depth of the nodes, and used to stop traversal beyond a given `maxDepth`.

``````/**
* Breadth first traversal leverages a [Queue] (FIFO).
*/
startNode: T,
maxDepth: Int = Int.MAX_VALUE): String {
//
// Setup.
//

// Mark all the vertices / nodes as not visited. And keep track of sequence
// in which nodes are visited, for return value.
class Visited {
val traversalList = mutableListOf<T>()

val visitedSet = mutableSetOf<T>()

fun isNotVisited(node: T): Boolean = !visited.contains(node)

}
}

val visited = Visited()

// Keep track of the depth of each node, so that more than maxDepth nodes
// aren't visited.
val depthMap = mutableMapOf<T, Int>().apply {
for (node in graph.adjacencyMap.keys) this[node] = Int.MAX_VALUE
}

// Create a queue for BFS.
class Queue {
val deck: Deque<T> = ArrayDeque<T>()
fun add(node: T, depth: Int) {
// Add to the tail of the queue.
// Record the depth of this node.
depthMap[node] = depth
}

}
}

fun isNotEmpty() = deck.isNotEmpty()
fun remove() = deck.remove()
}

val queue = Queue()

//
// Algorithm implementation.
//

// Initial step -> add the startNode to the queue.

// Traverse the graph
while (queue.isNotEmpty()) {
// Remove the item at the head of the queue.
val currentNode = queue.remove()
val currentDepth = depthMap[currentNode]!!

if (currentDepth <= maxDepth) {
if (visited.isNotVisited(currentNode)) {
// Mark the current node visited and add to traversal list.
}
}

}

return visited.traversalList.toString()
}
``````

## BFS and DFS traversal for binary trees #

To see a similar implementation of BFS and DFS traversal for binary trees, please refer to the Binary-Trees tutorial. Note that the binary tree traversal algorithm doesn’t need to have a map to mark visited nodes.

## Stacks and Queues # 