【问题标题】:Maze backtracking horizontal move迷宫回溯水平移动
【发布时间】:2019-11-24 19:32:53
【问题描述】:

在迷宫运动中的老鼠中,当老鼠水平移动时,我遇到了问题。我已经将老鼠定义为首先向下移动(如果有的话),然后向右然后向左移动。问题在于,当它走到一条死胡同并试图找到赖特路径时,老鼠会混淆左右两边。路径存储在数组中。出口在底部的任何地方。老鼠可以向任何方向移动。 (0,3) 是开始。

0 = 免费通过

1 = 被阻止

请看下面的例子:

1 1 1 0 1 1 1
1 1 1 0 1 1 1
1 0 0 0 1 0 1
1 0 1 0 1 0 0
1 1 1 0 1 1 1
1 0 0 0 0 0 1
1 0 1 1 1 0 1
0 0 1 1 1 0 1
0 1 1 1 0 1 1

路径:(0,3) (1,3) (2,3) (3,3) (4,3) (5,3) (5,4) (5,5) (6,5) (7,5) (6,5) (5,5) (5,4) (5,5) (6,5) (7,5) (6,5) (5,5) (5,4) (5,5)...

在此示例中,位于 (5,4) 处的老鼠没有选择向左移动,而是循环前一个路径。 我真的在努力寻找解决方案。有人知道吗?

这是我的一些代码:

public boolean solveRatMaze(int maze[][], int x, int y, int sol[][], Stack stack) {
        if ((x == maze.length-1 && isValidPlace(maze, x, y)) { //when (x,y) is the bottom right room
            sol[x][y] = 0;
            stack.push(String.valueOf(x));
            stack.push(String.valueOf(y));
            return true;
        }
        if(isValidPlace(maze, x, y) == true) {     //check whether (x,y) is valid or not
            sol[x][y] = 0; //set 0, when it is valid place
            if (solveRatMaze(maze,x+1, y, sol, stack) == true)       //when x direction is blocked, go for bottom direction
                return true;    //when x direction is blocked, go for bottom direction
            if (solveRatMaze(maze, x, y + 1, sol, stack) == true)         //find path by moving right direction
                return true;     //when x direction is blocked, go for bottom direction
            if (solveRatMaze(maze, x, y - 1, sol, stack) == true)         //find path by moving left direction
                return true;

            sol[x][y] = 0;         //if both are closed, there is no path
            return false;
        }
        return false;
    }

isValidPlace 只检查地点是否在 数组,值为 0(非阻塞)

sol[][] 是一个表示最终路径的数组。所有值为 1 除了路径值为 0

maze[][] 是给定的数组

【问题讨论】:

    标签: java backtracking maze


    【解决方案1】:

    您可以实现一个简单的堆栈“visitedpaths”,它存储您已经访问过的每个坐标,并告诉老鼠不要走这些路径。

    为此,你需要初始化一个栈和栈顶:

    public int[] visitedpaths;    
    private int top = -1 ; // that allows you to free up space to store values
    

    然后实现一个简单的push(int v):

    public void push( int v){ 
        top = top+1;
        top = v;
    }
    

    因此,每次鼠标移动时,它都会将图块存储在堆栈中。

    那么你必须通过修改第二个“if”来确保它不会进入访问过的瓷砖

    【讨论】:

      猜你喜欢
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多