Posts

Showing posts from June, 2017

How to implement depth first search algorithm(DFS) using java.

Image
DFS  (Depth first search) Traversal  algorithm can be applied to either Tree or Graph. fig.1 Consider above bi-directional graph, where in there are 10 nodes. If one wants to traverse from node-0 to node-9 Using DFS then in below sequence, nodes will be discovered. node-0 will be added to the stack{0}. node-0 will be removed and node-1 & 7 will be added{1,7}. node-7 will be removed and node-6 & 8 will be added {1,6,8}. node-8 will be removed and node-2 will be added{1,6,2}. node-2 will be removed and node-3 & 5 will be added{1,6,3,5}. node-5 will be removed and node-4 will be added as node-2 & 3 are already visited{1,6,3,4}. node-4 will be removed and node-9 will be added{1,6,3,9}. node-9 will be removed{1,6,3}. node-3 will be removed{1,6}. node-6 will be removed{1}.  node-1 will be removed{}. So, {0,7,8,2,5,4,9,3,6,1} will be the node traversal order. Solution: Below is the implementation of DFS in java using  Stack as a d...

How to implement breadth first search algorithm (BFS) in java.

Image
BFS  (Breadth first search) Traversal  algorithm can be applied to either Tree or Graph. fig.1 Consider above bi-directional graph, where in there are 10 nodes. If one wants to traverse from node-0 to node-9 Using BFS then in below sequence, nodes will be discovered. Start from node-0: In, Hop-I, Nodes 1 & 7 will be discovered. In, Hop-II, Nodes 2, 8 & 6 will be discovered. In, Hop-III, Nodes 3 & 5 will be discovered. In, Hop-IV, Node 4 will be discovered. In, Hop-V, Node 9 will be discovered. Solution: Below is the implementation of BFS in java using  Queue as a data structure , package com.mayank4java.algorithms; import java.util.LinkedList; import java.util.Queue; public class BFSTraversalAlgorithm { private int[][] graph; private boolean[] isVisited; public BFSTraversalAlgorithm(int noOfNodes) { graph = new int[noOfNodes][noOfNodes]; isVisited = new boolean[noOfNodes]; } public void addLink(int srcNode, ...

Differences between Tree & Graph Data-Structures.

Image
Howdy folks! 😊 You know, almost every real time scenarios can be represented using either Graphs or Trees.Like from Facebook network or Linkedin network or cities on a map or electical network or structure of your organisation where you are working or family tree structure and so on... Then why not take out some time and understand the differences between Graph and Tree data structures.               Tree                      Graph 1 Tree has directions. Graph can be uni-directional Or bi-directional both. 2 Tree do not have self-loops. Graph can also have self-loops. 3 Between two nodes only one path can exists. There can be multiple paths between two nodes. 4 All trees can be graph. That is tree can be considered as DAG(Directional acyclic graph with the restriction that a child can only have o...