我在此问题上需要帮助。我想使用递归解决NXN二进制矩阵。问题是我认为我的递归实施不正确。在这个问题中,我只允许向右和向下。我已经检查了ISSAFE()方法,并且一切似乎都根据1 = true返回true或false,0 = 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();
}
}
}
我相信这是您要寻找的解决方案:
public class Main2 {
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.solveAndPrintMaze(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;
}
int solmaze[][]= {
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}};
boolean solveMaze(int maze[][],int x,int y){
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+1, y,maze)==true && solveMaze(maze,x+1,y)==true){// down
solmaze[x][y]=1;
return true;
}
if(isSafe(x, y+1,maze)==true && solveMaze(maze,x,y+1)==true){//right
solmaze[x][y]=1;
return true;
}
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();
}
}
void solveAndPrintMaze(int maze[][],int x,int y) {
solveMaze(maze, x, y);
printmaze(solmaze);
}
}
在您第一次致电solveMaze
时,第二个 if
为true(((0,0)是安全的&amp;那里有一个),因此您返回true
而没有打印任何东西。/p>
也许如果您解释了要做的事情,可以帮助修复它(很可能是通过删除它)。
您实际上并未在此处尝试递归。要以您尝试的方式启动递归,您必须从内部调用您的SolveMaze方法。
我错了。正确答案由下面的Scott给出。