Advertisement
pervej56

BFS.n

Mar 24th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package bfs.algorithm;
  7.  
  8. import java.util.Iterator;
  9. import java.util.LinkedList;
  10. import java.util.Queue;
  11. import java.util.Scanner;
  12.  
  13. /**
  14. *
  15. * @author Masud pervej
  16. */
  17. public class BFSAlgorithm {
  18.  
  19. /**
  20. * @param args the command line arguments
  21. */
  22. public static void main(String[] args) {
  23. Scanner in = new Scanner(System.in);
  24. System.out.println("Input Max Node Number:");
  25. int maxNodeNumber = in.nextInt();
  26. int[][] matrix = new int[100][100];
  27. int[] vis = new int[100];
  28. int[] level = new int[100];
  29. System.out.println("Input Graph:");
  30. for(int i = 0; i <= maxNodeNumber; i++)
  31. {
  32. for(int j = 0; j <= maxNodeNumber; j++){
  33. matrix[i][j] = in.nextInt();
  34. }
  35. vis[i] = 0;
  36. }
  37. System.out.println("Input Array: ");
  38. for(int i = 0; i <= maxNodeNumber; i++)
  39. {
  40. for(int j = 0; j <= maxNodeNumber; j++)
  41. {
  42. System.out.print(matrix[i][j] + " ");
  43. }
  44. System.out.println("");
  45. }
  46. System.out.println("Starting Node:");
  47. int startNode = in.nextInt();
  48. Queue<Integer> q = new LinkedList<>();
  49. q.add(startNode);
  50. vis[0] = 1;
  51. level[startNode] = 0;
  52.  
  53. while(q.size() > 0)
  54. {
  55. int u = q.peek();
  56. q.remove();
  57. for(int i = 0; i <= maxNodeNumber; i++){
  58.  
  59. if(matrix[u][i] == 1 && vis[i] == 0){
  60. q.add(i);
  61. vis[i] = 1;
  62. level[i] = level[u] + 1;
  63. }
  64. }
  65. }
  66. System.out.println("Nodes\tLevel");
  67. for (int i = 0; i <= maxNodeNumber; i++)
  68. {
  69. System.out.println(i + " --> " +level[i]);
  70. }
  71.  
  72. }
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement