迷路(行列)を解決するためのクラス用のプロジェクトがありますが、これは簡単ですが、検証するif文に問題がありますその数がパスの一部であるかどうかを調べるために、行列セルの使い勝手を調べます。行列のセルに関する記述が真でない場合(Java)
ここで私が作成したテスト迷路です:
// 0 = start
// 1 = path
// 2 = wall
// 3 = end
// 5 = tried
// 6 = final path
int [][] maze = {{2,2,2,0,2,2,2,2,2,2},
{2,2,2,1,2,2,1,1,1,2},
{2,2,2,1,2,2,2,2,1,2},
{2,2,2,1,2,2,2,1,1,2},
{2,2,1,1,2,2,1,2,1,1},
{2,1,1,0,2,2,2,2,2,2},
{2,1,2,0,2,2,2,2,2,2},
{2,1,1,0,2,2,2,2,2,2},
{2,2,3,0,2,2,2,2,2,2},};
そしてここでは、現在のセルが上を歩くことが有効であるかどうかを確認する方法である:
private boolean valid (int row, int column) {
boolean result = false;
// checks if cell is inside of the matrix
if (row >= 0 && row < maze.length &&
column >= 0 && column < maze[0].length) {
// checks if cell is not blocked, if it has previously been tried or it's the end
if (maze[row][column] == 1 || maze[row][column] == 3 || maze[row][column] == 0 || maze[row][column] == 5) {
result = true;
}else{
result = false;
}
}
return result;
}
私は」print文を使用してからは、問題がおそらく入れ子にされたif文にあることがわかりました。しかし、解決方法にある、わからない別の問題があるかもしれません。
public boolean solve(int row, int column) {
boolean solved = false;
if (valid(row, column)) {
maze[row][column] = 5;
if (maze[row][column] == 1 || maze[row][column] == 0){
if(!solved){//it's going to call the function it self and move if possible.
solved = solve(row + 1, column); // South
if (!solved)
solved = solve(row, column + 1); // East
if (!solved)
solved = solve(row - 1, column); // North
if (!solved)
solved = solve(row, column - 1); // West
}
if (solved) // part of the final path
maze[row][column] = 7;
}else if (maze[row][column] == 3) {
solved = true;
System.out.println("lol the end");
}
//exception here not to leave the maze and case there's no 0
}
return solved;
}
これは、デバッガが存在する理由です。私はあなたのIDEのデバッガを使用する方法を学ぶ時間を費やすでしょう。 – OldProgrammer
まあ、すべてが真でなければ、それは一度比較して、偽を返します – Stultuske
私はテストしていませんが、この行を 'maze [row] [column] = 5;'と呼ぶと、 if(5!= 0 OR 5!== 0){'maze [row] == 1 || maze [row] [column] == 0){' 1) '、それはそれが言うことです)または何かが欠けている...? – Frakcool