我知道这是一个常见话题,但其他帖子都不能帮助我完成我的计划。
在这个迷宫中,我们必须读取一个文件,其中第一行包含数组的宽度和高度,第二行包含起始点E
和第三行MazeRunner
的协调。 1}}数组开始。我必须关注所有0's
,直到找到退出。
以下是一个例子:
8 7
0 3
1 1 1 1 1 E 1
1 0 0 0 1 0 1
1 0 1 0 0 0 1
1 1 1 0 1 1 1
1 0 0 0 0 0 1
1 0 1 1 1 0 1
1 1 0 0 0 0 1
0 1 0 1 1 1 1
在下面的代码中,readFile方法正常工作。我有一个问题,想弄清楚如何利用我的堆栈(在另一个文件中定义)。solveMaze方法启动得很好但是当涉及到有2个或更多零附近的点时我们目前的观点是它只是跟随它找到的导致无限循环的第一个方向。显然,我找不到回溯的方法..
Coords类也在另一个文件中定义,它只是创建一个点。
import java.io.*;
public class Maze{
private static boolean foundExit = false; /* Decides if the maze has a possible exit or not. */
private static int row, col;
private static Stack<Coords> stack = new Stack<Coords>();
private static char[][] MazeRunner;
private static int width, height;
private static int rowCoord,colCoord;
public static void readFile(){
File file = null;
BufferedReader reader = null;
int counter=0;
try {
file = new File("C:/Users/user01/workspace/p1/src/thiseas.txt");
} catch (NullPointerException e) {
System.err.println("File not found.");
}
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
System.err.println("Error opening file!");
}
try{
String line=reader.readLine();
String[] split=line.split(" ");
height = Integer.parseInt(split[0]);
width = Integer.parseInt(split[1]);
counter++;
line=reader.readLine();
split=line.split(" ");
rowCoord=Integer.parseInt(split[0]);
colCoord=Integer.parseInt(split[1]);
counter++;
MazeRunner=new char[height][width];
char[] ch;
while((line=reader.readLine())!=null){
ch = line.toCharArray();
for(int i = 0;i < 2*width-1;i+=2){
MazeRunner[counter-2][i/2] = ch[i];
}
counter++;
}
}catch (IOException e) {
System.out.println("Error reading line " + counter + ".");
}
solveMaze(rowCoord, colCoord);
}
private static void solveMaze(int a, int b) {
row = a;
col = b;
Coords coor=new Coords(row,col); //coordinations
stack.push(coor);
int j=0; //counts how many '0' are near our pointer
while (foundExit == false) {
if (col > 0 && MazeRunner[row][col-1] == '0') { //goes left
if(col-1 == 0) {
foundExit = true;
}else {
coor.setCol(col-1);
j++;
stack.push(hold);
}
}
if (col < width && MazeRunner[row][col+1] == '0') { //goes right
if(col+1 == width) {
foundExit = true;
}else if(j==0){
coor.setCol(col+1);
j++;
stack.push(hold);
}
}
if (row > 0 && MazeRunner[row-1][col] == '0') { //goes up
if(row-1 == 0) {
foundExit = true;
}else {
coor.setRow(row-1);
j++;
stack.push(hold);
}
}
if(row<height && MazeRunner[row+1][col] == '0'){ //goes down
if(row+1 == height) {
foundExit = true;
}else{
coor.setRow(row+1);
j++;
stack.push(hold);
}
}
row = coor.getRow();
col = coor.getCol();
//row and col will get wrong values because hold changes
coor= stack.peek();
}
System.out.println("The maze has been solved!. ");
System.out.println("Exit coordinations: " + coor.toString());
}
public static void main(String[] args) {
readFile();
}
}
任何帮助将不胜感激!