import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class Maze
{
private int[][] maze;
private boolean exitFound;
public Maze()
{
exitFound = false;
maze = new int[0][0];
}
public Maze(int size, String line)
{
exitFound=false;
maze = new int[size][size];
int spot=0;
for(int r= 0; r<maze.length; r++)
{
for(int c =0; c<maze[r].length; c++)
{
maze[r][c]=(line.charAt(spot*2)-48);
spot++;
}
}
}
public void checkForExitPath(int r, int c)
{
if (r >= 0 && r <maze.length &&c >= 0 && c < maze[0].length && maze[r][c] == 1)
{
checkForExitPath(r + 1, c);
checkForExitPath(r - 1, c);
checkForExitPath(r, c + 1);
checkForExitPath(r, c - 1);
maze[r][c] = 7;
if (r == maze.length-1 && c == maze[0].length-1){
this.exitFound =true;
}
}
}
public String toString()
{
String hol = "";
for(int i = 0; i<maze.length; i++){
for(int j = 0; j<maze[0].length; j++){
hol += " ";
if(maze[i][j] == 7){
hol += "1";
}
else
{
hol += maze[i][j];
}
}
hol += "\n";
}
if(this.exitFound)
{
hol+= "exit found";
}
else {
hol += "exit not found";
}
return hol;
}
}
這是我的迷宮類中的方法checkForExitPath不工作,或者至少我想是因爲每次我這個亞軍類迷宮求解器無法找到出口
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.*;
public class MazeRunner
{
public static void main() throws IOException
{
Scanner file = new Scanner(new File("maze.dat"));
while(file.hasNext())
{
int size = file.nextInt();
file.nextLine();
Maze test = new Maze(size, file.nextLine());
test.checkForExitPath(0,0);
out.println(test);
}
}
}
唯一的輸出我得到的運行迷宮求解是沒有找到出口,但我可以找到出口。 我正在遞歸地做這件事。
你試過調試嗎? –
是的,但我不知道如何解決這個問題,即方法關閉後第一個如果說明 –