Implementing BFS in Java

import java.io.*;
import java.util.*;
class anbfs
{
	public static void main(String args[])throws IOException
	{
		int m[][]=new int[50][50];	
		//Input
		System.out.println("Enter n:");
		int n;
		BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
		n= Integer.parseInt(obj.readLine());
		int i,j,k,l=0;
		System.out.println("Enter matrix:");
		for(i=0;i<n;i++)
		{
			for(j=0;j<n;j++)
			{
				m[i][j] = Integer.parseInt(obj.readLine());
			}
		}
		//Printing entered values
		System.out.println("Entered matrix is:");
		for(i=0;i<n;i++)
		{
			for(j=0;j<n;j++)
			{
				System.out.print(m[i][j]+" ");
			}
			System.out.println();
		}
		//processing
		int q[] = new int[100];
		//inserted first element
		q[0]=1;
		int qpos=1;
		i=0;
		while (i<qpos)
		{	
			for(j=i;j<n;j++)
			{
				if (m[i][j]!=0)
				{
					for(k=0;k<qpos;k++)
					{
						l=0; //flag
						if (q[k]==j+1)
						{
							l=1;
						}
					}
					if (l==0)
					{
						q[qpos]=j+1;
						qpos++;
					}
				}
			}
			i++;
		}
		System.out.print("BFS Output:\n");
		for(j=0;j<qpos;j++)
		{
			System.out.print(q[j]+" ");
		}
	}
}

/* OUTPUT
Enter n:
8
Enter matrix:
0
1
1
1
0
0
0
0
1
0
0
0
1
1
0
0
1
0
0
0
0
0
0
0
1
0
0
0
0
0
1
1
0
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
1
0
0
0
0
Entered matrix is:
0 1 1 1 0 0 0 0 
1 0 0 0 1 1 0 0 
1 0 0 0 0 0 0 0 
1 0 0 0 0 0 1 1 
0 1 0 0 0 0 0 0 
0 1 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
0 0 0 1 0 0 0 0 
BFS Output:
1 2 3 4 5 6 7 8 

*/

One thought on “Implementing BFS in Java”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.