【发布时间】:2017-12-27 22:44:08
【问题描述】:
我在这个问题上需要帮助。我想使用递归来求解 NxN 二进制矩阵。问题是我认为我的递归实现在某种程度上是不正确的。在这个问题中,我只能向右和向下走。我检查了 issafe() 方法,根据 1=true 和 0=false,一切似乎都返回 true 或 false。如果我运行运行程序,什么都不会显示。任何帮助将非常感激。
public class Main {
public static void main(String[] args) {
int maze[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{0, 1, 0, 0},
{1, 1, 1, 2}
};
Maze rat = new Maze();
rat.solveMaze(maze, 0, 0);
}
}
public class Maze {
int maze[][];
int mazeSize;
int EXIT=2;
public Maze() {
mazeSize=4;
maze = new int[mazeSize][mazeSize];
}
// check is its safe to traverse
public Boolean isSafe(int x, int y, int maze[][]){
if (x>=0 && x<mazeSize && y>=0 && y<mazeSize && maze[x][y]==1){
return true;
}
else return false;
}
boolean solveMaze(int maze[][],int x,int y){
int solmaze[][]= { {0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}};
if(maze[x][y]==EXIT){
solmaze[x][y]=1;
printmaze(solmaze);
return true;
}
if(isSafe(x, y,maze) && maze[x][y]==1){
solmaze[x][y]=1;
return true;
}
if(isSafe(x, y,maze)==true && solveMaze(maze,x+1,y)==true){// down
solmaze[x][y]=1;
}
if(isSafe(x, y,maze)==true && solveMaze(maze,x,y+1)==true){//right
solmaze[x][y]=1;
}
solmaze[x][y]=0;
return false;
}
void printmaze(int maze[][]){//print maze
for(int i=0;i<maze.length;i++){
for(int j=0;j<maze.length;j++){
System.out.print(maze[i][j]);
}
System.out.println();
}
}
}
【问题讨论】: