Introduction to Graph with Breadth First Search

1. Development of Composite Rotation Matrix.
2. Develop and arm matrix for Adept-1 SCARA robot.
3. Inverse Kinematics for Adept-I SCARA Robot.
4. Eight Queen Problem.
5. Graph Structures and Paths.
6. Wumpus world problem.
7. Water Jug Problem.
8. Knight.s Tour.
9. Crypto Arithmetic Problems.
10. Implementing Searching algorithm.
The n-queens problem in Java
A classic combinatorial problem is to place n queens on an n × n chess board so that
no queen threatens any other queen, that is, so that no two queens are on the same
row, column, or diagonal. In order to reduce this solution space, it can now be
assumed without loss of generality, that the ith queen is placed in the ith row,
thereby avoiding those two queens can be in the same row.
All solutions to the n-queens problem can therefore be represented as ntuples (c1, c2,
. . . cn), where ci is column on which queen i is placed, and no two ciscan be the
same. Each queen is assigned a different column, so the only thing left to check is
whether two queens are in the same diagonal. The rows are now numbered from
bottom to top and the columns are numbered from left to right Hence the bottom left
corner has the coordinates (0,0) and the top left corner (n-1,0). With this numeration,
two queens with the coordinates (i, ci) and (j, cj) are in the same ascending diagonal
if j −i == cjci. They are in the same descending diagonal if j −i == ci − cj. Thus, in
order to check whether two queens are in the same diagonal, no matter in which
direction, it is sufficient to check whether |j − i| == |cj − ci| or not.
Java version of the n-queens problem is given below:
?
1 /**
change this template, choose Tools | Templates
2 ** To
and open the template in the editor.
3 */
4 package queens;
5
6 /**
7 *
* @author ACHCHUTHAN
8 */
9 public class Queens {
10
int[] x;
11
12
public Queens(int N) {
13
x = new int[N];
14
}
15
16
public boolean canPlaceQueen(int r, int c) {
17
/**
* Returns TRUE if a queen can be placed in row r and column c.
18
* Otherwise it returns FALSE. x[] is a global array whose first
19
(r-1)
20
* values have been set.
21
*/
for (int i = 0; i < r; i++) {
22
if (x[i] == c || (i - r) == (x[i] - c) ||(i - r) == (c - x[i]))
23
{
24
return false;
25
}
26
}
return true;
27
}
28
29
public void printQueens(int[] x) {
30
int N = x.length;
31
for (int i = 0; i < N; i++) {
32
for (int j = 0; j < N; j++) {
if (x[i] == j) {
33
System.out.print("Q ");
34
} else {
35
System.out.print("* ");
36
}
}
37
System.out.println();
38
}
39
System.out.println();
40
}
41
42
public void placeNqueens(int r, int n) {
/**
43
* Using backtracking this method prints all possible placements of
44
n
45
* queens on an n x n chessboard so that they are non-attacking.
46
*/
for (int c = 0; c < n; c++) {
47
if (canPlaceQueen(r, c)) {
48
x[r] = c;
49
if (r == n - 1) {
50
printQueens(x);
51
} else {
placeNqueens(r + 1, n);
52
53
54
55
56
57
58
59
60
61
62
63
64}
65
66
67
68
69
70
71
72
73
74
75
}
}
}
}
public void callplaceNqueens() {
placeNqueens(0, x.length);
}
public static void main(String args[]) {
Queens Q = new Queens(8);
Q.callplaceNqueens();
}
Output of this program is given bellow :
run:
* Q *
* * *
Q * *
* * Q
* * Q
Q * *
* * *
* Q *
*
Q
*
*
*
*
Q
*
BUILD SUCCESSFUL (total time: 1 second)
Introduction to Graph with Breadth First Search(BFS) and Depth First
Search(DFS) Traversal Implemented in JAVA
By bijulsoni, 1 Jan 2013
4.80 (23 votes)

Download source code - 5.53 KB
Introduction
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. I was not able to find a simple, precise explanation for beginners on this topic. So, I
decided to write an article for graph. 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.
What is a Graph?
Graphs are one of the most interesting data structures in computer science. Graphs and the trees
are somewhat similar by their structure. In fact, tree is derived from the graph data structure.
However there are two important differences between trees and graphs.
1. Unlike trees, in graphs, a node can have many parents.
2. The link between the nodes may have values or weights.
Graphs are good in modeling real world problems like representing cities which are connected by
roads and finding the paths between cities, modeling air traffic controller system, etc. These
kinds of problems are hard to represent using simple tree structures. The following example
shows a very simple graph:
In the above graph, A,B,C,D,E,F are called nodes and the connecting lines between these nodes
are called edges. The edges can be directed edges which are shown by arrows; they can also be
weighted edges in which some numbers are assigned to them. Hence, a graph can be a
directed/undirected and weighted/un-weighted graph. In this article, we will discuss undirected
and un-weighted graphs.
Graph Representation in Programming Language
Every graph has two components, Nodes and Edges. Let’s see how these two components are
implemented in a programming language like JAVA.
1. Nodes
Nodes are implemented by class, structures or as Link-List nodes. As an example in JAVA, we
will represent node for the above graph as follows:
Collapse | Copy Code
//
Class Node
{
Char data;
Public Node(char c)
{
this.data=c;
}
}
//
2. Edges
Edges represent the connection between nodes. There are two ways to represent edges.
Adjacency Matrix
It is a two dimensional array with Boolean flags. As an example, we can represent the edges for
the above graph using the following adjacency matrix.
In the given graph, A is connected with B, C and D nodes, so adjacency matrix will have 1s in
the ‘A’ row for the ‘B’, ‘C’ and ‘D’ column.
The advantages of representing the edges using adjacency matrix are:
1. Simplicity in implementation as you need a 2-dimensional array
2. Creating edges/removing edges is also easy as you need to update the Booleans
The drawbacks of using the adjacency matrix are:
1. Increased memory as you need to declare N*N matrix where N is the total number of nodes.
2. Redundancy of information, i.e. to represent an edge between A to B and B to A, it requires to
set two Boolean flag in an adjacency matrix.
In JAVA, we can represent the adjacency matrix as a 2 dimensional array of integers/Booleans.
Adjacency List
It is an array of linked list nodes. In other words, it is like a list whose elements are a linked list.
For the given graph example, the edges will be represented by the below adjacency list:
Graph Traversal
The breadth first search (BFS) and the depth first search (DFS) are the two algorithms used for
traversing and searching a node in a graph. They can also be used to find out whether a node is
reachable from a given node or not.
Depth First Search (DFS)
The aim of DFS algorithm is to traverse the graph in such a way that it tries to go far from the
root node. Stack is used in the implementation of the depth first search. Let’s see how depth first
search works with respect to the following graph:
As stated before, in DFS, nodes are visited by going through the depth of the tree from the
starting node. If we do the depth first traversal of the above graph and print the visited node, it
will be “A B E F C D”. DFS visits the root node and then its children nodes until it reaches the
end node, i.e. E and F nodes, then moves up to the parent nodes.
Algorithmic Steps
1.
2.
3.
4.
Step 1: Push the root node in the Stack.
Step 2: Loop until stack is empty.
Step 3: Peek the node of the stack.
Step 4: If the node has unvisited child nodes, get the unvisited child node, mark it as traversed
and push it on stack.
5. Step 5: If the node does not have any unvisited child nodes, pop the node from the stack.
Breadth First Search (BFS)
This is a very different approach for traversing the graph nodes. The aim of BFS algorithm is to
traverse the graph as close as possible to the root node. Queue is used in the implementation of
the breadth first search. Let’s see how BFS traversal works with respect to the following graph:
If we do the breadth first traversal of the above graph and print the visited node as the output, it
will print the following output. “A B C D E F”. The BFS visits the nodes level by level, so it will
start with level 0 which is the root node, and then it moves to the next levels which are B, C and
D, then the last levels which are E and F.
Algorithmic Steps
1.
2.
3.
4.
Step 1: Push the root node in the Queue.
Step 2: Loop until the queue is empty.
Step 3: Remove the node from the Queue.
Step 4: If the removed node has unvisited child nodes, mark them as visited and insert the
unvisited children in the queue.
Graph Traversals
A primary problem concerning the graphs is the reachability. A number of graph problems
involve traversal of a graph. Traversal of a graph means visiting each of its nodes exactly once.
This is accomplished by visiting the nodes in a systematic manner. Two commonly used
techniques of graph traversal are depth-first search (DFS) and breadth-first search (BFS). These
algorithms work for both directed and undirected graphs.
Depth-First Search
Depth-first search is a generalization of the preorder traversal of a tree. DFS can serve as a
structure around which many other efficient graph algorithms can be built.
As an example of dfs, suppose in the graph of the following figure, we start at node A.
Depth-First Search
class Node
{ int label; // vertex label
Node next; // next node in list
Node( int b ) // constructor
{ label = b; }
}
class Graph
{ int size;
Node adjList[];
int mark[];
Graph(int n) // constructor
{ size = n;
adjList = new Node[size];
mark = new int[size]; // elements of mark are initialized to 0
}
public void createAdjList(int a[][]) // create adjacent lists
{
Node p; int i, k;
for( i = 0; i < size; i++ )
{ p = adjList[i] = new Node(i); //create first node of ith adj. list
for( k = 0; k < size; k++ )
{ if( a[i][k] == 1 )
{ p.next = new Node(k); // create next node of ith adj. list
p = p.next;
}
}
}
}
public void dfs(int head) // recursive depth-first search
{ Node w; int v;
mark[head] = 1;
System.out.print( head + ” “);
w = adjList[head];
while( w != null)
{ v = w.label;
if( mark[v] == 0 ) dfs(v);
w = w.next;
}
}
}
DfsDemo.java
class DfsDemo
{ public static void main(String[] args)
{ Graph g = new Graph(5); // graph is created with 5 nodes
int a[][] = { {0,1,0,1,1}, {1,0,1,1,0}, {0,1,0,1,1},
{1,1,1,0,0}, {1,0,1,0,0}};
g.createAdjList(a);
g.dfs(0); // starting node to dfs is0 (i.e., A)
}
}
Output of this program is: 0 1 2 3 4
Here, 0 is for A, 1 is for B, 2 is for C, 3 is for D, and 4 is for E
Breadth-First Search
Posted by mohammedmoulana on March 26, 2012
Another systematic way of visiting the nodes is called breadth-first search (bfs). The approach is
called “breadth-first” because from each node v that we visit we search as broadly as possible by
next visiting all nodes adjacent to v.
The breadthFirstSearch algorithm inserts a node into a queue, which we assume is initially
empty. Every entry in the array mark is assumed to be initialized to the value unvisited. If the
graph is not connected, bfs must be called on a node of each connected component. Note that in
bfs we must mark a node visited before inserting it into the queue, to avoid placing it on the
queue more than once. The algorithm terminates when the queue becomes empty.
We assume the graph is represented by an adjacency list and is globally available. The algorithm
depends on the availability of an implementation of a queue of integers (here, a simple queue is
assumed; not circular queue). Three methods relating to queue: qinsert(), qdelete(), and
isEmpty() are to be properly defined before the method for bfs is defined.
Breadth-First Search
class Node
{ int label; // vertex label
Node next; // next node in list
Node( int b ) // constructor
{ label = b; }
}
class Graph
{ int size;
Node adjList[];
int mark[];
Graph(int n) // constructor
{ size = n;
adjList = new Node[size];
mark = new int[size];
}
public void createAdjList(int a[][]) // create adjacent lists
{ Node p; int i, k;
for( i = 0; i < size; i++ )
{ p = adjList[i] = new Node(i);
for( k = 0; k < size; k++ )
{ if( a[i][k] == 1 )
{ p.next = new Node(k);
p = p.next;
}
} // end of inner for-loop
} // end of outer for-loop
} // end of createAdjList()
public void bfs(int head)
{ int v; Node adj;
Queue q = new Queue(size);
v = head;
mark[v] = 1;
System.out.print(v + ” “);
q.qinsert(v);
while( !q.IsEmpty() ) // while(queue not empty)
{
v = q.qdelete();
adj = adjList[v];
while( adj != null )
{ v = adj.label;
if( mark[v] == 0 )
{ q.qinsert(v);
mark[v] = 1;
System.out.print(v + ” “);
}
adj = adj.next;
}
}
}
} // end of Graph class
class Queue
{ private int maxSize; // max queue size
private int[] que; // que is an array of integers
private int front;
private int rear;
private int count; // count of items in queue
public Queue(int s) // constructor
{ maxSize = s;
que = new int[maxSize];
front = rear = -1;
}
public void qinsert(int item)
{ if( rear == maxSize-1 )
System.out.println(“Queue is Full”);
else { rear = rear + 1;
que[rear] = item;
if( front == -1 ) front = 0;
}
}
public int qdelete()
{ int item;
if( IsEmpty() )
{ System.out.println(“\n Queue is Empty”);
return(-1);
}
item = que[front];
if( front == rear ) front = rear = -1;
else front = front+1;
return(item);
}
public boolean IsEmpty()
{ return( front == -1 ); }
}
class BfsDemo
{ public static void main(String[] args)
{ Graph g = new Graph(5);
int a[][] = { {0,1,0,1,1}, {1,0,1,1,0}, {0,1,0,1,1},
{1,1,1,0,0}, {1,0,1,0,0}};
g.createAdjList(a);
g.bfs(0);
}
}
Output of this program is: 0 1 3 4 2