数字迷宫求解算法

时间:2016-08-15 22:01:42

标签: java maze

我正在研究一种独特类型迷宫的求解器,称为“数字迷宫”。基本上你所处的每个位置都是一个数字(1-4),表示下一个可能的移动位置(向上,向下,对角线)。这是一个说明,以澄清我在说什么。

enter image description here

最后,每个职位只能访问一次。目标是能够找到通过迷宫的最长路径。

目前,我可以成功找到每个位置的可能移动,并遍历迷宫中所有可能的路径。该程序不知道迷宫的“结束”是什么,但这很容易实现。我目前遇到的问题是我不知道如何实现“路径记忆”以分析所有可能的路径并找出哪个路径最长。基本上我需要一种方法来存储所有不同的路径,然后分析它们。我尝试使用ArrayList<String> MovePath这样做,但最终无效。我认为这样的整个递归方面让我感到沮丧。我的代码的所有重要部分都发布在下面。任何指针都会受到赞赏。

private static String changeString(String currentstring, String addendum) {
        return currentstring + addendum;
    }

static ArrayList<String> solve(int X, int Y, String path, ArrayList<String> MovePath, int[][] PuzzleBoard) {

        if (PuzzleBoard[X][Y] == 0) {
            //If current position is blank, don't attempt to find moves

    } else {

        ArrayList<Point> AllMoves = FindMoves(PuzzleBoard, X, Y); //Find possible moves from current board location based on piece type


        for (int i = 0; i < AllMoves.size(); i++) {//Iterate through possible moves
            PuzzleBoard[X][Y] = 0; //set current position to 0 (empty)
            X = (int) AllMoves.get(i).getX();//get move X coordinate
            Y = (int) AllMoves.get(i).getY();//get move Y coordinate

            String xstring = String.valueOf(X);
            String ystring = String.valueOf(Y);

            path = changeString(path, xstring);//Adds the current X coordinate to a string
            path = changeString(path, ystring);//Adds the current Y coordinate to a string

            MovePath.add(path);

            solve(X, Y, path, MovePath, PuzzleBoard);

        }
    }

    return MovePath;
}

public static void main(String[] args) {

   int[][] BoardArray = new int[][]{
            {4, 0, 0, 0, 1, 0},
            {0, 1, 1, 1, 1, 0},
            {0, 1, 0, 0, 3, 0},
            {0, 0, 2, 0, 0, 0},
            {0, 0, 0, 0, 0, 0},
            {0, 0, 3, 0, 1, 9}
        //0 = empty
       //9 = end

    int x = 0; //starting x
    int y = 0; //starting y
    String paths = "";
    ArrayList<String> MovePath = new ArrayList<String>();
    ArrayList<String> Answer = new ArrayList<String>();

    Answer = solve(x, y, paths, MovePath, BoardArray)

    String longestpath = Collections.max(Answer, Comparator.comparing(s -> s.length()));
    System.out.println(longestpath);

}

}

1 个答案:

答案 0 :(得分:0)

我的第一个想法是添加一个包含最大路径的var,它将在所有完成路径后更新。存储递归的深度,并在完成后将其与最大值进行比较。

相关问题