Advertisement
Guest User

dfs

a guest
Feb 6th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. import java.util.InputMismatchException;
  2.  
  3. import java.util.Scanner;
  4.  
  5. import java.util.Stack;
  6.  
  7.  
  8.  
  9. public class DFS
  10.  
  11. {
  12.  
  13. private Stack<Integer> stack;
  14.  
  15.  
  16.  
  17. public DFS()
  18.  
  19. {
  20.  
  21. stack = new Stack<Integer>();
  22.  
  23. }
  24.  
  25.  
  26.  
  27. public void dfs(int adjacency_matrix[][], int source)
  28.  
  29. {
  30.  
  31. int number_of_nodes = adjacency_matrix[source].length - 1;
  32.  
  33.  
  34.  
  35. int visited[] = new int[number_of_nodes + 1];
  36.  
  37. int element = source;
  38.  
  39. int i = source;
  40.  
  41. System.out.print(element + "\t");
  42.  
  43. visited[source] = 1;
  44.  
  45. stack.push(source);
  46.  
  47.  
  48.  
  49. while (!stack.isEmpty())
  50.  
  51. {
  52.  
  53. element = stack.peek();
  54.  
  55. i = element;
  56.  
  57. while (i <= number_of_nodes)
  58.  
  59. {
  60.  
  61. if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
  62.  
  63. {
  64.  
  65. stack.push(i);
  66.  
  67. visited[i] = 1;
  68.  
  69. element = i;
  70.  
  71. i = 1;
  72.  
  73. System.out.print(element + "\t");
  74.  
  75. continue;
  76.  
  77. }
  78.  
  79. i++;
  80.  
  81. }
  82.  
  83. stack.pop();
  84.  
  85. }
  86.  
  87. }
  88.  
  89.  
  90.  
  91. public static void main(String...arg)
  92.  
  93. {
  94.  
  95. int number_of_nodes, source;
  96.  
  97. Scanner scanner = null;
  98.  
  99. try
  100.  
  101. {
  102.  
  103. System.out.println("Enter the number of nodes in the graph");
  104.  
  105. scanner = new Scanner(System.in);
  106.  
  107. number_of_nodes = scanner.nextInt();
  108.  
  109.  
  110.  
  111. int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
  112.  
  113. System.out.println("Enter the adjacency matrix");
  114.  
  115. for (int i = 1; i <= number_of_nodes; i++)
  116.  
  117. for (int j = 1; j <= number_of_nodes; j++)
  118.  
  119. adjacency_matrix[i][j] = scanner.nextInt();
  120.  
  121.  
  122.  
  123. System.out.println("Enter the source for the graph");
  124.  
  125. source = scanner.nextInt();
  126.  
  127.  
  128.  
  129. System.out.println("The DFS Traversal for the graph is given by ");
  130.  
  131. DFS dfs = new DFS();
  132.  
  133. dfs.dfs(adjacency_matrix, source);
  134.  
  135. }catch(InputMismatchException inputMismatch)
  136.  
  137. {
  138.  
  139. System.out.println("Wrong Input format");
  140.  
  141. }
  142.  
  143. scanner.close();
  144.  
  145. }
  146.  
  147. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement