Graph data structures - Searching
Previously we looked at an introduction to graph data structures and designed a very basic Graph implementation. I also mentioned that the main things we would likely want to do with a graph is search/explore the graph.There are two primary tools that we will use to explore graphs - these are basic computer science concepts, and should be familiar to everyone who has studied computer science at uni and faced graphs before.
Depth First Search (DFS)
search as deep as we can one route before backtracking (e.g. select a neighbour to the root node, visit that neighbour, then select a neighbour from that node and visit - continue this until we reach a node that we cannot follow any more edges from, and then backtrack up the graph considering alternate neighbours at each step)
Below is a simple Java implementation of DFS using recursion to handle the backtracking.
Breadth First Search (BFS)
(image also from wikipedia)
BFS is also fairly simple, and pretty close to DFS but it uses a Queue (FIFO) structure rather than a stack to visit nodes from the root down first. Below is example code of BFS implemented in Java.
0 comments: