Creating a maze solving algorithm in Java

前端 未结 5 1357
萌比男神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: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;
     }
    

提交回复
热议问题