Java - Util.Inputmismatchexception Java - Util.Scanner Java - Util.Stack

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

1. import java.util.InputMismatchException; 2. import java.util.Scanner; 3. import java.util.Stack; 4. 5. public class DepthLimitedSearch 6. { 7. 8. 9. 10. 11. 12. 13. 14. 15.

16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. visited[destination] == 0) 37. 38. { stack.push(destination); while (!stack.isEmpty()) { element = stack.peek(); destination = element; while (destination <= numberOfNodes) { if (depth < MAX_DEPTH) { if (adjacencyMatrix[element][destination] == 1 && System.out.println(source + " at depth " + depth); stack.push(source); visited[source] = 1; depth = 0; public void depthLimitedSearch(int adjacencyMatrix[][], int source) { int visited[] = new int[numberOfNodes + 1]; int element, destination; int depth = 0; } public DepthLimitedSearch(int numberOfNodes) { this.numberOfNodes = numberOfNodes; this.stack = new Stack<Integer>(); private Stack<Integer> stack; private int numberOfNodes; private static final int MAX_DEPTH = 3;

39. 40. 41. depth); 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. } } } stack.pop(); depth--; } } else { }

visited[destination] = 1; depth++; System.out.println(destination + " at depth " + element = destination; destination = 1;

return; destination++;

public static void main(String... arg) { int number_of_nodes, source; Scanner scanner = null; try { System.out.println("Enter the number of nodes in the graph"); scanner = new Scanner(System.in); number_of_nodes = scanner.nextInt(); int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1]; System.out.println("Enter the adjacency matrix"); for (int i = 1; i <= number_of_nodes; i++) for (int j = 1; j <= number_of_nodes; j++) adjacency_matrix[i][j] = scanner.nextInt(); System.out.println("Enter the source for the graph"); source = scanner.nextInt();

76. 77. 78. source); 79. 80. 81. 82. 83. 84. 85. 86. } } }

System.out.println("The Depth limited Search Traversal of Max Depth 3 is"); DepthLimitedSearch depthLimitedSearch = new DepthLimitedSearch(number_of_nodes); depthLimitedSearch.depthLimitedSearch(adjacency_matrix,

} catch (InputMismatchException inputMismatch) { System.out.println("Wrong Input format"); scanner.close();

$javac DepthLimitedSearch.java $java DepthLimitedSearch Enter the number of nodes in the graph 5 Enter the adjacency matrix 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 Enter the source for the graph 1 The Depth limited Search Traversal 1 at depth 0 2 at depth 1 3 at depth 2 4 at depth 3 of Max Depth 3 for the graph is given by

You might also like