Depth First Search – DFS


This is the second post in the series of tree/graph traversal. As in the last post breadth first search I used a concrete example with sample code in Java to explain the traversal algorithm. So without further a due here is the java code for depth first search (dfs)

	public void depthFirstTraversal(Node rootNode) {

		Stack s = new Stack();
		s.add(rootNode);
		rootNode.visited = true;
		while(!s.isEmpty()){
			Node n = s.pop();
			System.out.print(n.data +  " ");
			for(Node adj : n.adjacentNodes){
				if(!adj.visited){
					adj.visited = true;
					s.push(adj);
				}
			}
		}
	}

As opposed to breadth first traversal, depth first traversal uses stack to push the newly expanded node instead of Queue. For further reference read this

Advertisements

2 thoughts on “Depth First Search – DFS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s