forked from balajimanoharan/Search
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.java
More file actions
99 lines (92 loc) · 2.47 KB
/
DFS.java
File metadata and controls
99 lines (92 loc) · 2.47 KB
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
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;
public class DFS {
ArrayList<String> maze=new ArrayList<String>();
int[][] visited;
Node startNode;
Stack<Node> stack = new Stack<Node>();
int mazeRBound=0, mazeBBound=0;
int nodesExpanded=0;
public static void main(String[] args) throws IOException {
DFS dfs= new DFS();
dfs.readInput();
Node end = dfs.search();
dfs.findPath(end);
//System.out.println(end.xPos+":"+end.yPos);
}
private void findPath(Node node) {
System.out.println(node.xPos+":"+node.yPos);
if(node.parent==null)
return;
else
findPath(node.parent);
}
private Node search() {
while(!stack.isEmpty()){
Node node = stack.pop();
nodesExpanded++;
int xPos = node.xPos, yPos = node.yPos;
//System.out.println(xPos+";"+yPos);
if(maze.get(yPos).charAt(xPos)=='.')
return node;
if(maze.get(yPos).charAt(xPos+1)!='%'){
Node child = new Node(xPos+1,yPos,node);
if(visited[xPos+1][yPos]!=1){
visited[xPos+1][yPos]=1;
stack.push(child);
}
}
if(maze.get(yPos-1).charAt(xPos)!='%'){
Node child = new Node(xPos,yPos-1,node);
if(visited[xPos][yPos-1]!=1){
visited[xPos][yPos-1]=1;
stack.push(child);
}
}
if(maze.get(yPos+1).charAt(xPos)!='%'){
Node child = new Node(xPos,yPos+1,node);
if(visited[xPos][yPos+1]!=1){
visited[xPos][yPos+1]=1;
stack.push(child);
}
}
if(maze.get(yPos).charAt(xPos-1)!='%'){
Node child = new Node(xPos-1,yPos,node);
if(visited[xPos-1][yPos]!=1){
visited[xPos-1][yPos]=1;
stack.push(child);
}
}
}
return null;
}
private void readInput() throws IOException {
int startRow=0, startCol=0;
BufferedReader br = new BufferedReader(new FileReader("E:/Fall 2013/AI/Assignments/1/Input/openMaze.lay"));
int i=-1;
String str;
while(((str = br.readLine())!=null)){
//System.out.println(str);
i++;
if(str.contains("P")){
startCol = str.indexOf('P');
startRow = i;
}
maze.add(str);
}
startNode = new Node(startCol, startRow, null);
stack.push(startNode);
mazeBBound = maze.size();
mazeRBound = maze.get(0).length();
visited = new int[mazeRBound][];
for(int j=0;j<mazeRBound;j++){
visited[j]=new int[mazeBBound];
}
visited[startCol][startRow]=1;
//System.out.println(startRow+":"+startCol+":"+maze.size()+":"+mazeRBound+":"+maze.get(mazeBBound-1).charAt(mazeRBound-1));
br.close();
}
}