0
需要在正確的方向上進行類別分配。我已閱讀其他職位,提到創建一個變量/方法來存儲路徑,但不知道如何得到它... 編輯9/28/16 能夠達到迷宮的終點,但還沒有想出 如何打印只採取的路徑;我真的需要陷入遞歸迷宮
import java.io.*;
import java.util.*;
public class Maze
{
private static int rows, cols, startRow, startCol, nextRow, nextCol;
private static int endRow = 3;
private static int endCol = 34;
private static char[][] mazeBoard;
//private static char start = 'S';
private static char end = 'E';
//private boolean finish = false;
private char[][] explored = new char[rows][cols];
//construct the maze board
public Maze() throws FileNotFoundException
{
Scanner in = new Scanner(new File("maze.txt"));
rows = in.nextInt();
cols = in.nextInt();
startRow = in.nextInt();
startCol = in.nextInt();
//fill out the mazeBoard
mazeBoard = new char[rows][cols];
int i = 0;
while (in.hasNextLine())
{
String inLine = in.nextLine();
if (inLine.isEmpty())
{
continue;
}
for (int j = 0;j < cols; j++)
{
char nextChar = inLine.charAt(j);
mazeBoard[i][j] = nextChar;
System.out.print(nextChar);
}
System.out.println();
i++;
}
in.close();
}
//updated the move method from void to boolean
public boolean move(int row, int col, int prevRow, int prevCol)
{
boolean finish = false;
prevRow = row;
prevCol = col;
//show location
System.out.println("row: " + row + " col: " + col);
//base case1 to check for out of bounds and not the previous position
if (row < 0 || col < 0 || row >= rows || col >= cols || row != prevRow || col != prevCol)
{ return false; }
//base case2 to see if reached exit/end point
if (row == endRow && col == endCol)
{
System.out.println("Found the exit!");
return true;
}
//base case3 to check for wall
if (mazeBoard[row][col] == '+' || mazeBoard[row][col] == '*')
{ return false; }
mazeBoard[row][col] = '*';
//try to move down
if (move(row + 1, col, prevRow, prevCol))
{ return true; }
//try to move right
if (move(row, col + 1, prevRow, prevCol))
{ return true; }
//try to move up
if (move(row - 1, col, prevRow, prevCol))
{ return true; }
//try to move left
if (move(row, col - 1, prevRow, prevCol))
{ return true; }
row = prevRow;
col = prevCol;
return false;
}
public static void main(String[] args) throws FileNotFoundException
{
Maze maze = new Maze();
maze.move(startRow, startCol);
}
}
==== 所以我不知道如何實現一個方法來跟蹤路徑行進,任何指針將不勝感激!
一些關於你想達到什麼的解釋將不勝感激。沒有仔細觀察你的代碼,我想你想解決迷宮?如果是這樣,你是否必須使用特定的算法或解決它?此外,你能否描述你的實現和你遇到的問題更詳細? – Turing85
歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)適用於此處。在您發佈代碼並準確描述問題之前,我們無法有效幫助您。 – Prune
請參閱本堆棧溢出問題清單,以幫助您提出一個問題,以幫助您朝正確的方向發展。 http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist –