The objective of this article is to provide a basic introduction about graphs and the commonly used algorithms used for traversing the graph, BFS and DFS. Breadth First Search (BFS) and Depth First Search (DFS) are the two popular algorithms asked in most of the programming interviews. This article will help any beginner to get some basic understanding about what graphs are, how they are represented, graph traversals using BFS and DFS.
|
public class Main {
/**
* @param args
*/
public static void main(String[] args)
{
//Lets create nodes as given as an example in the article
Node nA=new Node('A');
Node nB=new Node('B');
Node nC=new Node('C');
Node nD=new Node('D');
Node nE=new Node('E');
Node nF=new Node('F');
//Create the graph, add nodes, create edges between nodes
Graph g=new Graph();
g.addNode(nA);
g.addNode(nB);
g.addNode(nC);
g.addNode(nD);
g.addNode(nE);
g.addNode(nF);
g.setRootNode(nA);
g.connectNode(nA,nB);
g.connectNode(nA,nC);
g.connectNode(nA,nD);
g.connectNode(nB,nE);
g.connectNode(nB,nF);
g.connectNode(nC,nF);
//Perform the traversal of the graph
System.out.println("DFS Traversal of a tree is ------------->");
g.dfs();
System.out.println("\nBFS Traversal of a tree is ------------->");
g.bfs();
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.