Advertisement
rana1704

BFS

Apr 11th, 2019
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. package BFS;
  2.  
  3.  
  4. import java.util.LinkedList;
  5. import java.util.Queue;
  6. import java.util.Scanner;
  7.  
  8. /**
  9.  *
  10.  * @author Green
  11.  */
  12. class BFSRun
  13. {
  14.     int graph[][] =
  15.     {
  16.         {0,1,1,0,0},
  17.         {1,0,1,1,0},
  18.         {1,1,0,0,1},
  19.         {0,1,0,0,1},
  20.         {0,0,1,1,0}
  21.                     };
  22.     int vis[];
  23.     int N;
  24.     int level[];
  25.     BFSRun()
  26.     {
  27.         System.out.println("Enter Node number");
  28.         Scanner in = new Scanner(System.in);
  29.         N= in.nextInt();
  30.         vis = new int[N];
  31.         level = new int[N];
  32.         BFS();
  33.         Print();
  34.     }
  35.     void BFS()
  36.     {
  37.         int s = 0;
  38.         Queue<Integer> q = new LinkedList<>();
  39.         q.add(s);
  40.         while(!q.isEmpty())
  41.         {
  42.             int u=q.poll();
  43.             vis[u]=1;
  44.             for(int v=0;v<N;v++)
  45.             {
  46.                 if(graph[u][v]==1 && vis[v]==0)
  47.                 {
  48.                     q.add(v);
  49.                     level[v] = level[u] + 1;
  50.                 }
  51.             }
  52.         }
  53.     }
  54.  
  55.     void Print() {
  56.         System.out.println("Node\tLevel");
  57.         for(int i=0;i<N;i++)
  58.         {
  59.             System.out.println(""+i+"\t"+ level[i]);
  60.         }
  61.     }
  62. }
  63. public class BFS {
  64.  
  65.     /**
  66.      * @param args the command line arguments
  67.      */
  68.     public static void main(String[] args) {
  69.         // TODO code application logic here
  70.         BFSRun mydfs = new BFSRun();
  71.        
  72.     }
  73.    
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement