繁体   English   中英

使用递归和回溯解决迷宫问题

[英]Solving the maze problem using recursion and backtracking

我正在尝试使用Java解决迷宫问题,代码仅使用两个方向(向右和向下)完全可以正常工作,但是,我想使其在所有方向上搜索/移动,从而引发错误(堆栈溢出)。

下面的代码:

  public class Maze {

    int n,m,startX,startY,endX,endY;

    public Maze(int n,int m) {
        this.n = n;
        this.m = m;
    }

    public void findLocation(int[][]array)
    {
        for(int i=0; i < array.length;i++)
            for(int j = 0 ; j <array[i].length;j++)
                {if(array[i][j] == 3)
                {
                    startX = i;
                    startY = j;
                }
                if(array[i][j] == 9)
                {
                    endX = i;
                    endY = j;
                }
                }
    }

    public boolean isSafe(int[][]array,int x, int y)
    {
        return (x>=0 && x < n && y>=0 && y<m && array[x][y]!=0);
    }

    public boolean solution(int[][] array)
    {
        int[][]sol = new int[n][m];

        findLocation(array);
        if(solutionUtil(array,startX,startY,sol)==false)
        {
            System.out.println("no solution");
            return false;
        }

        printsolution(sol);
        return true;
    }

private void printsolution(int[][] sol) {
        // TODO Auto-generated method stub
    for(int i=0; i < sol.length;i++)
    {   for(int j = 0 ; j <sol[i].length;j++)
             System.out.print(" " + sol[i][j] + 
                     " "); 
        System.out.println(); 
             }
    }

private boolean solutionUtil(int[][] array, int x, int y, int[][] sol) {
        // TODO Auto-generated method stub
        if(x == endX && y == endY)
        {
            sol[x][y] = 1;
            return true;
        }

        if(isSafe(array,x,y))
        {
            sol[x][y] = 1;

            if(x!=0)
            {
                if(solutionUtil(array,x-1,y,sol)==true)
                    return true;
            }
            if(y!=0)
            {
                if(solutionUtil(array,x,y-1,sol)==true)
                    return true;
            }

            if(solutionUtil(array,x+1,y,sol)==true)
                return true;
            if(solutionUtil(array,x,y+1,sol)==true)
                return true;

            sol[x][y] =0;
            return false;
        }

        return false;
    }

public static void main(String[] args)
{

    int[][] array = {{0, 0, 0, 0}, 
            {1, 1, 3, 1}, 
            {0, 1, 0, 0}, 
            {1, 1, 1, 9}};

    Maze run = new Maze(4,4);
    run.solution(array);


}

}

起点是3,终点是9,1表示它可以移动,0表示它不能移动(障碍),我该如何避免错误,因此,在所有方向上都具有遍历的能力,这是错误的我的代码?

您无需检查之前是否未尝试过该步骤,因此您的代码可以进入重复步骤的无限循环。

将解决方案数组传递给isSafe并检查之前是否未访问过坐标:

public boolean isSafe(int[][] array, int x, int y, int[][] sol) {
    return (x >= 0 && x < n && y >= 0 && y < m && array[x][y] != 0)
        && sol[x][y] == 0;
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM