0% found this document useful (0 votes)
55 views

Title: Implement Bread-First Search: Department of Computer Science and Engineering

This document provides information about implementing breadth-first search (BFS) on graphs represented using adjacency matrices. It includes sections on representing graphs as adjacency matrices, the BFS algorithm, implementing BFS in Java, sample inputs and outputs, and exercises for students to complete including detecting cycles in a graph using BFS.

Uploaded by

Sazeda Sultana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Title: Implement Bread-First Search: Department of Computer Science and Engineering

This document provides information about implementing breadth-first search (BFS) on graphs represented using adjacency matrices. It includes sections on representing graphs as adjacency matrices, the BFS algorithm, implementing BFS in Java, sample inputs and outputs, and exercises for students to complete including detecting cycles in a graph using BFS.

Uploaded by

Sazeda Sultana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Department of

Computer Science and Engineering

Title: Implement Bread-First Search

Artificial Intelligence Lab


CSE 404

Green University of Bangladesh


1 Objective(s)
• To understand how to represent a graph using adjacency matrix.
• To understand how Bread-First Search (BFS) works.

2 Problem analysis
Every graph is a set of points referred to as vertices or nodes which are connected using lines called edges.
The vertices represent entities in a graph. Edges, on the other hand, express relationships between entities.
Hence, while nodes model entities, edges model relationships in a network graph. A graph G with a set of V
vertices together with a set of E edges is represented as G= (V, E). Both vertices and edges can have additional
attributes that are used to describe the entities and relationships. Figure 1 depicts a simple graph with five
nodes and seven edges.

Figure 1: A simple graph

Adjacency Matrix:
Vertices are labelled (or re-labelled) with integers from 0 to V (G) - 1. A two-dimensional array “matrix”
with dimensions V (G) * V (G) contains a 1 at matrix [j] [k] if there is an edge from the vertex labelled j to the
vertex labelled k, and a 0 otherwise.Table:1 represents the graph of figure:1;
3 Algorithm (Adjacency Matrix)
Step 1. Set i=0, e = Number of edges.
Step 2. e (number of edge) < i (Decision). • if no - continue with the step 7.
Step 3. Take the values of edge by giving the adjacency nodes [j], [k] (A, B, C, D, E=0,1,2,3,4).
Step 4. matrix[j][k] =matrix[k][j] =1.
Step 5. Increment i (i++).
Step 6. continue with the step 2.
Step 7. Stop.

4 Flowchart

5 Implementation in Java
1 public class AdjacencyMatrix {
2 static int[][]matrix= new int[20][20];// 2D array that will contain the graph
3 public static void main(String[] args) {
4 int e=7, n=5;//e is number of edges, n is number of vetices
5 Inmatrix(e);
6 System.out.println("Output:");
7 for(int i=0;i<n;i++){
8 for(int j=0;j<n;j++){
9 System.out.print(matrix[i][j]+" ");
10 }
11 System.out.println("");
12 }
13
14
15 }
16 static void Inmatrix(int e){
17 Scanner sn =new Scanner(System.in);
18 System.out.println("Enter The Edges:");
19 int i;
20 char j,k;
21
22 for(i=0;i<e;i++){// this loop runs e times to take the all edges.
23 j=sn.next().charAt(0);
24 k=sn.next().charAt(0);
25 matrix[(int)j−65][(int)k−65]=matrix[(int)k−65][(int)j−65]=1;
26 // An undirected edge has both ways access between the nodes.
27 //If A to B has a way to go then B to A has the same way.
28
29 }
30
31 }

6 Sample Input/Output (Compilation, Debugging & Testing)


Input:
Enter The Edges:
AB
AC
AD
AE
BC
CD
CE
Output:
01111
10100
11011
10100
10100

7 Bread First Search


Breadth First Search (BFS) algorithm traverses a graph in a breadth Ward motion and uses a queue to remember
to get the next vertex to start a search, when a dead end occurs in any iteration.
As in the example given above, BFS algorithm traverses from A to B to E to F first then to C and G lastly to
D. It employs the following rules.

8 Algorithm of BFS
A standard BFS implementation puts each vertex of the graph into one of two categories:
1.Visited
2.Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.

The algorithm works as follows:


Step 1. Start by putting any one of the graph’s vertices at the back of a queue.
Step 2. Take the front item of the queue and add it to the visited list.
Step 3. Create a list of that vertex’s adjacent nodes. Add the ones which aren’t in the visited list to the back
of the queue.
Step 4. Keep repeating steps 2 and 3 until the queue is empty.

The graph might have two different disconnected parts so to make sure that we cover every vertex, we can
also run the BFS algorithm on every node

9 Implementation in Java
1 import java.util.*;
2 public class BreadFS {
3
4 static char[] c={’A’,’B’,’C’,’D’,’E’,’F’,’G’,’S’};
5 static int e[]={2,2,2,2,2,2,3,3};
6 static int list[][]={{3,7},{4,7},{5,7},{0,6},{1,6},{2,6},{3,4,5},{0,1,2}};//
adjacency list of graph figure 1.
7 static int[] checked=new int[20];
8 static int[] que=new int[20];
9 static int first=0,last=0;
10 public static void main(String[] args) {
11
12 int i,j,n;
13 enq(7);
14 while(first<last){
15 n=dq();
16 for(i=0;i<e[n];i++){
17 if(notChecked(list[n][i])==1)
18 enq(list[n][i]);
19 }
20 }
21
22
23 }
24 static int notChecked(int n){// this method checks the node visited or not
25 if(checked[n]==1)
26 return 0;
27 return 1;
28 }
29
30 static void enq(int n){//this methods is used to enqueue node
31 checked[n]=1;
32 que[last]=n;
33 last++;
34 }
35
36 static int dq(){// this method is used to dequeue a node.
37 //printf("%c ",que[first]+65);
38 System.out.print(c[que[first]]+" ");
39 first++;
40 return que[first−1];
41 }
42 }

10 Sample Input/Output (Compilation, Debugging & Testing)


Output(BSF traversal sequence):
SABCDEFG

11 Lab Task (Please implement yourself and show the output to the
instructor)
1. Write a program to perform BSF traversal on a dynamic graph from user.
2. Write a program to find the level of each node using BFS.

12 Lab Exercise (Submit as a report)


• Write a program to detect the cycle in a graph using BFS.

13 Policy
Copying from internet, classmate, seniors, or from any other source is strongly prohibited. 100% marks will be
deducted if any such copying is detected.

You might also like