Creating a maze solving algorithm in Java

前端 未结 5 1356
萌比男神i
萌比男神i 2021-02-01 10:56

I\'ve been assigned with the task of creating a maze solver in Java. Here\'s the assignment:

Write an application that finds a path through a maze.  
The maze sh         


        
相关标签:
5条回答
  • 2021-02-01 11:24

    You need to separate your program in two phases. The first one is the initialization, where you read the maze description and the initial position of the player. After this you have a data structure to represent the board. The second one is the actual game, where there should be 3 abstractions:

    • The player state. In your case it is pretty simple, its actual position on the board.
    • The maze itself, which is the environment. It should have functions telling you if you have visited a given position, to mark position you have visited, where is the goal,the next reachable cells, etc...
    • The logic, which is the search algorithm.

    Any of these should be able to change without much change of the others. For example, you may be asked to improve your search algorithm, or a problem where you have more than one goal. The easiness of switching from the current problem to a slightly modified one is the real metric of a program design.

    0 讨论(0)
  • 2021-02-01 11:27

    I tried to implement this using DFS algorithm utilizing some Java OOP concepts.

    See complete solution on my github repository

    private boolean solveDfs() {
        Block block = stack.peekFirst();
        if (block == null) {
            // stack empty and not reached the finish yet; no solution
            return false;
        } else if (block.equals(maze.getEnd())) {
            // reached finish, exit the program
            return true;
        } else {
            Block next = maze.getNextAisle(block);
            // System.out.println("next:" + next);
            if (next == null) {
                // Dead end, chose alternate path
                Block discard = stack.pop();
                discard.setInPath(false);
                // System.out.println("Popped:" + discard);
            } else {
                // Traverse next block
                next.setVisited(true);
                next.setInPath(true);
                stack.push(next);
            }
        }
        return solveDfs();
    

    }

    0 讨论(0)
  • 2021-02-01 11:33

    enter image description here

    I submitted a similar answer here Maze Solving Algorithm in C++.

    To have a chance in solving it, you ought to:

    • Create a Solve() routine and recursively call itself:
      • if 1st, 2nd, 3rd, ... are true Solve has succeeded in finding a solution
      • if 1st, 2nd, 3rd, ... contains a false, it has to backtrack and find another way
    • You need to build a buffer of places you've been to avoid infinite loops
      • as you make moves it needs to keep tabs on it
      • when we hit a dead end, we need to erase bad moves
      • we can implement the above by burning in a guess and removing it if it's wrong

    Here's some pseudo code for the solution.

    boolean solve(int X, int Y)
    {
        if (mazeSolved(X, Y))
        {
            return true;
        }
    
        // Test for (X + 1, Y)
        if (canMove(X + 1, Y))
        {
            placeDude(X + 1, Y);
            if (solve(X + 1, Y)) return true;
            eraseDude(X + 1, Y);
        }
    
        // Repeat Test for (X - 1, Y), (X, Y - 1) and (X, Y + 1)
        // ...
    
        // Otherwise force a back track.
        return false;
     }
    
    0 讨论(0)
  • 2021-02-01 11:38

    As amit has said, you should first read the entire maze and store it as a 2 dimensional array. This lets you see the whole maze without having to solve it line-by-line.

    Since you'll first need to find the size of the array, you should read the text file into a List of Strings.

    List<String> strs = new ArrayList<String>();
    
    //Pseudocode, choose however you want to read the file
    while(file_has_next_line) {
        strs.add(get_next_line);
    }
    

    The size of the List gives you the number of rows, and assuming it's always a grid, you can use split().length, (count spaces + 1) or count the symbols on any one of the Strings to get the number of columns.

    Easiest way to store the map data is with a 2D array of booleans. Where true is a wall and false is empty space.

    boolean[][] wallMap = new boolean[rows][cols];
    
    for(int i = 0; i < wallMap.length; i++) {
    
        //Separate each symbol in corresponding line
        String[] rowSymbols = strs.get(i).split(" ");
    
        for(int j = 0; j < wallMap[i].length; j++) {
    
            //Ternary operator can be used here, I'm just keeping it simple
            if(rowSymbols[j].equals("X")) {
                 wallMap[i][j] = true;
            } else {
                 wallMap[i][j] = false;
            }
    
        }
    
    }
    

    Now that you have the map data stored in an array it's much easier to traverse the map and make your choices, you can either use a ready-made algorithm (see amit's answer) or make your own. As this is homework, you should try and think up your own.

    Have fun.

    0 讨论(0)
  • 2021-02-01 11:43

    You probably should module your program - as I can understand it, you are reading the maze from file and trying to solve it at the same time.

    A better approach will be to split the program into 2 distinct parts:

    1. read the input file and create a matrix with all the data
    2. solve the maze from given matrix

    Doing so will help you to build and test each part seperately, which will probably result in better, more reliable program.

    Solving the maze could be done by a simple BFS, which is similar to what your algorithm originally suggested , which is a DFS

    0 讨论(0)
提交回复
热议问题