Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package BFS;
- import java.util.LinkedList;
- import java.util.Queue;
- import java.util.Scanner;
- /**
- *
- * @author Green
- */
- class BFSRun
- {
- int graph[][] =
- {
- {0,1,1,0,0},
- {1,0,1,1,0},
- {1,1,0,0,1},
- {0,1,0,0,1},
- {0,0,1,1,0}
- };
- int vis[];
- int N;
- int level[];
- BFSRun()
- {
- System.out.println("Enter Node number");
- Scanner in = new Scanner(System.in);
- N= in.nextInt();
- vis = new int[N];
- level = new int[N];
- BFS();
- Print();
- }
- void BFS()
- {
- int s = 0;
- Queue<Integer> q = new LinkedList<>();
- q.add(s);
- while(!q.isEmpty())
- {
- int u=q.poll();
- vis[u]=1;
- for(int v=0;v<N;v++)
- {
- if(graph[u][v]==1 && vis[v]==0)
- {
- q.add(v);
- level[v] = level[u] + 1;
- }
- }
- }
- }
- void Print() {
- System.out.println("Node\tLevel");
- for(int i=0;i<N;i++)
- {
- System.out.println(""+i+"\t"+ level[i]);
- }
- }
- }
- public class BFS {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- // TODO code application logic here
- BFSRun mydfs = new BFSRun();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement