0
20 7
xxxxxxxxxxxxxxxxxxEx
x x xxxx x
x xxxxx xxxxx xx x
x xxxxx xxxxxxx xx x
x xx xx x
x xxxxxxxxxx xx x
xxxxxxxxxxxxSxxxxxxx
Finding a way through the maze, S is the starting 6 12. And ends at E, 0 18.
import java.util.*;
import java.io.*;
public class mazeSolver {
boolean wall = false;
char[][] maze;
boolean solved;
public mazeSolver(char[][] in_maze) {
maze = in_maze;
}
public void findPath(int row, int col) {
if (maze[row][col] == 'E') {
solved = true;
return;
}
maze[row][col] = 'b';
if (maze[row + 1][col] == ' ' || maze[row + 1][col] == 'E') {
findPath(row + 1, col);
}
else if (maze[row][col + 1] == ' ' || maze[row][col + 1] == 'E') {
findPath(row, col + 1);
}
else if (maze[row - 1][col] == ' ' || maze[row - 1][col] == 'E') {
findPath(row -1, col);
}
else if (maze[row][col - 1] == ' ' || maze[row][col - 1] == 'E') {
findPath(row, col - 1);
}
else {
wall = true;
return;
}
if (wall) {
wall = false;
findPath(row, col);
}
if (solved) {
maze[row][col] = '+';
}
}
public void printMaze(int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(maze[i][j]);
}
System.out.println();
}
}
public void solveCheck(int rows, int cols) {
boolean solveable = false;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] != '+') {
solveable = true;
}
break;
}
break;
}
if(!solveable){
System.out.println("S is unreachable");
}
}
也這是主要的類
import java.util.Scanner;
import java.io.File;
public class ADTmaze {
public static void main(String[] args) {
try {
Scanner myScanner = new Scanner(
new File("maze.txt"));
int numRows = myScanner.nextInt();
int numCols = myScanner.nextInt();
myScanner.nextLine();
int startX = 0;
int startY = 0;
// New maze
char[][] maze = new char[numRows][numCols];
System.out.println(numRows +","+ numCols);
for (int i = 0; i < numRows; i++) {
String nextLine = myScanner.nextLine();
for (int j = 0; j < numCols; j++) {
char nextChar = nextLine.charAt(j);
maze[i][j] = nextChar;
System.out.print(nextChar);
}
System.out.println();
}
// Solve the maze
mazeSolver newMaze = new mazeSolver(maze);
System.out.println();
newMaze.findPath(startX, startY);
newMaze.printMaze(numRows, numCols);
// Find the starting point
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (maze[i][j] == 'S') {
System.out.println("Starting coordinates: "
+ i + ", " + j);
startX = i;
startY = j;
}
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
得到一個錯誤,但它不會打印整個像上面的原始矩陣,我得到一個錯誤沒有找到線。不知道它錯在哪裏。我不知道在哪裏打印功能是怎麼了?
20,7
xxxxxxx
x x
x xxxxx
x xxxxx
x
x xxxxx
xxxxxxx
java.util.NoSuchElementException: No line found
在Java刪除此行\t xxxxxxxxxxxxxxxxxxEx XX XXXX X X爲XXXXX XXXXX XX X X爲XXXXX XXXXXXX XX X X XX XX X X XXXXXXXXXX XX X xxxxxxxxxxxxSxxxxxxx 查找通過的方式迷宮,S是開始的6 12.結束於E,0 18. –
我建議註釋掉主要的try/catch,以便從引發異常的位置獲得堆棧轉儲。如果輸入字符串的長度大於列的數量,則可以在print/build循環中獲得一個異常。如果數據文件的迷宮超出了宣稱的迷宮尺寸,我不確定你應該怎麼做。如果沒有額外的指示,我會忽略多餘的字符,並打印一條消息,如果其中任何一個字符是非空白的。 –