Application of BFS On Grid

Abhishek Raj
2 min readJul 16, 2021

--

Suppose you have a given a matrix as a map of nxm which contains dot(.) and hash(#) symbol in given matrix .Dot is consider as floor and hash is consider as wall .you can move left ,right ,up ,down through the floor .Find the number of room in that matrix.

fig.1

Solution :-

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class CSES1 {

static class Node{

int first;
int second;
Node(int x,int y)
{
first=x;
second=y;
}
}
static int z1;
static int z2;
static int a[]={-1,0,1,0}; // up,right,down,left
static int b[]={0,1,0,-1}; // up,right,down,left
static boolean visited[][] = new boolean[1000][1000];
public static void main(String[] args) {

String str;
int count=0;
Scanner sc = new Scanner(System.in);
z1 = sc.nextInt();
z2=sc.nextInt();
char ch[][]= new char[z1][z2];
for(int i=0;i<z1;i++)
{
for(int j=0;j<z2;j++)
{
str=sc.next();
ch[i][j]=str.charAt(0);
}
}

for(int i=0;i<z1;i++)
{
for(int j=0;j<z2;j++)
{
if(!visited[i][j] && ch[i][j]==’.’)
{

bfs(i,j,ch,visited);
count++;
}
}
}
System.out.println(count);

}

public static void bfs(int x,int y,char[][]ch,boolean[][] visited)
{
Queue<Node> q = new LinkedList<>();
q.add(new Node(x,y));
visited[x][y]=true;
while(!q.isEmpty())
{
int m=q.peek().first;
int n=q.peek().second;
q.poll();
for(int i=0;i<4;i++)
{

if(isValid(m+a[i],n+b[i],ch,visited) && ch[m+a[i]][n+b[i]]==’.’)
{
if(!visited[m+a[i]][n+b[i]])
{
visited[m+a[i]][n+b[i]]=true;
q.add(new Node(m+a[i],n+b[i]));
}
}
}
}

}

public static boolean isValid(int x,int y,char[][] ch,boolean[][] visited)
{
if(x<0 || x>(z1–1) || y<0|| y>(z2–1)|| visited[x][y]==true|| ch[x][y]==’#’)
{
return false;
}
return true;
}
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response