-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIDDFS.java
112 lines (100 loc) · 3.4 KB
/
IDDFS.java
1
2
3
4
5
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
37
38
39
40
41
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Joel Joseph
*/
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class IterativeDeepening {
/**
* @param args the command line arguments
*/
private Stack<Integer> stack;
private int numberOfNodes;
private int depth;
private int maxDepth;
private boolean goalFound = false;
public IterativeDeepening()
{
stack = new Stack<Integer>();
}
public void iterativeDeeping(int adjacencyMatrix[][], int destination)
{
numberOfNodes = adjacencyMatrix[1].length - 1;
while (!goalFound)
{
depthLimitedSearch(adjacencyMatrix, 1, destination);
maxDepth++;
}
System.out.println("\nGoal Found at depth " + depth);
}
private void depthLimitedSearch(int adjacencyMatrix[][], int source, int goal)
{
int element, destination = 1;
int[] visited = new int[numberOfNodes + 1];
stack.push(source);
depth = 0;
System.out.println("\nAt Depth " + maxDepth);
System.out.print(source + "\t");
while (!stack.isEmpty())
{
element = stack.peek();
while (destination <= numberOfNodes)
{
if (depth < maxDepth)
{
if (adjacencyMatrix[element][destination] == 1)
{
stack.push(destination);
visited[destination] = 1;
System.out.print(destination + "\t");
depth++;
if (goal == destination)
{
goalFound = true;
return;
}
element = destination;
destination = 1;
continue;
}
} else
{
break;
}
destination++;
}
destination = stack.pop() + 1;
depth--;
}
}
public static void main(String args[]) {
// TODO code application logic here
int number_of_nodes, destination;
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 destination for the graph");
destination = scanner.nextInt();
IterativeDeepening iterativeDeepening = new IterativeDeepening();
iterativeDeepening.iterativeDeeping(adjacency_matrix, destination);
}catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
scanner.close();
}
}