2 回答
TA贡献1847条经验 获得超7个赞
有很多解决方案,具体取决于您的需要。
一个简单的方法是,如果您希望用户尝试他们可以提供的不同 maze.txt 文件,则从命令行参数(即,从args
main 方法的参数)获取文件的路径。
您可以将主要方法主体更改为:
MazeSolver ms = new MazeSolver(args[0]);
当然,还需要进一步检查,但这与本练习无关。
然后,用户从终端运行您的程序:
java MazeSolver /path/to/their/maze.txt
/path/to/their/maze.txt
将args[0]
在您的主要方法中捕获。
TA贡献1963条经验 获得超6个赞
import java.util.Scanner;
import java.io.*;
public class MazeSolver {
private char[][] maze;
private int startX;
private int startY;
private int row;
private int col;
private int endX;
private int endY;
public MazeSolver (String fileName) {
try {
Scanner get = new Scanner(new FileReader(fileName));
row = get.nextInt(); // Integer.parseInt(sChar[0]);
col = get.nextInt(); //col = Integer.parseInt(sChar[2]);
maze = new char[row][col];
String mazeString = "";
// Read the entire file and store in a String called mazeString
while(get.hasNextLine()) {
mazeString += get.nextLine();
}
char[] temp = mazeString.toCharArray();
for(int x = 0; x < row * col; x++) {
maze[x/row][x%col] = temp[x];
}
}
catch (IOException e) {
System.out.println("\nFile cannot be found. Please try again: \n");
System.exit(0);
}
char start = 'S';
for(int i = 0; i < row; i++) {
for(int x = 0; x < col; x++) {
char setStart = maze[i][x];
if(setStart == start) {
startX = i;
startY = x;
}
}
}
char goal = 'G';
for(int i = 0; i < row; i++) {
for(int x = 0; x < col; x++) {
char setEnd = maze[i][x];
if(setEnd == goal) {
endX = i;
endY = x;
}
}
}
if (solveMaze(startX,startY)){
System.out.println("Solution Found");
printMaze();
}
else{
System.out.println("No solution Found");
printMaze();
}
}
public void printMaze() {
for(int r = 0; r < row; r++) {
for(int c = 0; c < col; c++) {
System.out.print(maze[r][c]);
}
System.out.println();
}
}
public boolean solveMaze(int x, int y) {
// Base case
if(x == endX && y == endY) {
maze[x][y] = 'G';
maze[startX][startY]='S';
return true;
}
// Out of bounds
if((x >= 0 && x < row && y >= 0 && y < col && maze[x][y] != 'X' && maze[x][y] != '.') == true) {
maze[x][y] = '.';
// Right
if(solveMaze(x + 1, y)) {
return true;
}
// Left
if(solveMaze(x - 1, y)) {
return true;
}
// Up
if(solveMaze(x, y - 1)) {
return true;
}
// Down
if(solveMaze(x, y + 1)) {
return true;
}
else {
maze[x][y] = '#';
return false;
}
}
else {
return false;
}
}
}
添加回答
举报