用Java创建一个迷宫解决算法

7

我被分配了一个任务,需要使用Java编写一个迷宫求解器。以下是任务要求:

Write an application that finds a path through a maze.  
The maze should be read from a file.  A sample maze is shown below.

O O O O O X O
X X O X O O X
O X O O X X X
X X X O O X O
X X X X O O X
O O O O O O O
X X O X X X O

字符'X'代表墙或者阻塞位置,字符'O'代表开放位置。假设迷宫的入口总是在右下角,出口总是在左上角。你的程序应该将输出写入文件。如果找到了一条路径,则输出文件应包含该路径。如果没有找到路径,则应向文件发送消息。请注意,一个迷宫可能有多条解决方案的路径,但在这个练习中,您只需要找到一条解决方案,而不是所有的解决方案。
您的程序应该使用堆栈来记录正在探索的路径,并在到达阻塞位置时回溯。
在编写代码之前,请确保编写完整的算法。可以自由创建任何其他类来帮助完成任务。
Here's my Algorithm:
1)Initialize array list to hold maze
2)Read text file holding maze in format
    o x x x x o
    o o x o x x
    o o o o o x
    x x x x o o
3)Create variables to hold numbers of columns and rows
3)While text file has next line
    A. Read next line
    B. Tokenize line
    C. Create a temporary ArrayList
    D. While there are tokens
        i. Get token
        ii. create a Point
        iii. add point to temp ArrayList
        iv. increment maximum number of columns
    E. Add temp to maze arraylist, increment max rows
    F. initialize a hold of points as max rows - 1
    G. Create a start point with x values as maximum number of rows - 1, and y values as maximum number of columns - 1
    H. Create stack of points and push starting location
    I. While finished searching is not done
        i. Look at top of stack and check for finish
        ii. check neighbors
        iii. is there an open neighbor?
            - if yes, update flags and push
            - if no, pop from stack
    J. Print solution
4. Done is true

无论如何,我设置了一个Points类,其中包含前进、后退、向左和向右移动的set/get方法,这些方法将返回布尔值,如下所示:
public class Points<E>
{
private int xCoord;
private int yCoord;
private char val;
private boolean N;
private boolean S;
private boolean E;
private boolean W;

public Points()
{
    xCoord =0;
    yCoord =0;
    val =' ';
    N = true;
    S = true;
    E = true;
    W = true;

}

public Points (int X, int Y)
{
        xCoord = X;
        yCoord = Y;

}

public void setX(int x)
{
    xCoord = x;
}
public void setY(int y)
{
    yCoordinate = y;
}

public void setNorth(boolean n)
{
    N = n;
}
public void setSouth(boolean s)
{
    S= s;
}
public void setEast(boolean e)
{
    E = e;
}

public void setWest(boolean w)
{
    W = w;
}

public int getX()
{
    return xCoord;

}

public int getY()
{
    return yCoord;
}
public char getVal()
{
    return val;
}

public boolean getNorth()
{
    return N;
}
public boolean getSouth()
{
    return S;
}

public boolean getEast()
{
    return E;
}
public boolean getWest()
{
    return W;
}

public String toString1()
{
    String result = "(" + xCoord + ", " +yCoord + ")";
    return result;
}

我在主程序中遇到了实际求解的问题。这是我的代码:

import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;


public class MazeSolve1
{
  public static void main(String[] args)
  {
//Create arrayList of Points
ArrayList<ArrayList<Points>> MAZE = new ArrayList<ArrayList<Points>>();
Scanner in = new Scanner(System.in);

//Read File in
System.out.print("Enter the file name: ");
String fileName = in.nextLine();
fileName = fileName.trim();
FileReader reader = new FileReader(fileName+".txt");
Scanner in2 = new Scanner(reader);

//Write file out
FileWriter writer = new FileWriter("Numbers.out");
PrintWriter out = new PrintWriter(writer);
boolean done = false;
int maxCol = 0;
int maxRow = 0;

while(!done) {

    //creating array lists
    while (in2.hasNextLine()) {
        //Read next line
        String nextLine = in2.nextLine();
        //Tokenize Line
        StringTokenizer st = new StringTokenizer(nextLine, " ");
        //Create temp ArrayList
        ArrayList<ArrayList<Points>> temp = new ArrayList<ArrayList<Points>>();

        //While there are more tokens
        while (st.hasNextToken()) {
            String token = st.nextToken();
            Points pt = new Points();
            temp.add(pt);
            maxCol++
        }
        MAZE.add(temp);
        maxRow++;
    }

    //create hold arraylist for max rows of maze -1 
    //create variables for start x and y coordinates
    ArrayList<ArrayList<Points>> hold = new ArrayList<ArrayList<Points>>();
    hold = MAZE.get(maxRow - 1);
    int startColumn = hold.get(maxCol - 1);
    int startRow = hold.get(maxRow - 1);
    Point start = new Point();
    start.setX(startColumn);
    start.setY(startRow);

    //initialize stack, and push the start position
    MyStack<Points> st = new ArrayStack<Points>();
    st.push(start.toString1());
    //south and east of start are edges of array
    start.setSouth(false);
    start.setEast(false);

    //while your position is not equal to point (0,0) [finish]
    while (st.peek() != "(0, 0)") {

        //getting the next coordinate to the North
        int nextY = start.getY() - 1;
        int nextX = start.getX();

        //if character to the North is an O it's open and the North flag is true
        if (hold.get(nextY) = 'O' && start.getNorth() == true) {
            //set flags and push coordinate
            start.setNorth(false);
            st.push(start.toString1());
        }
        //else pop from stack
        else { st.pop(); }

        //look at coordinate to the East
        nextX = start.getX() + 1;
        //if character to the East is a O and the East flag is true
        if (hold.get(nextX) = 'O' && start.getEast() == true) {
            //set flags and push coordinate
            start.setEast(false);
            st.push(start.toString1());
        }
        //else pop from stack
        else { st.pop(); }

        //look at coordinate to the South
        nextY = start.getY() + 1;
        //if character to the South is a O and the West flag is true
        if (hold.get(nextY) = 'O' && start.getSouth() == true) {
            //set flags and push coordinate
            start.setSouth(false);
            st.push(start.toString1());
        }
        //else pop from stack
        else { st.pop() }

        //keep looping until the top of the stack reads (0, 0)
    }

done = true;
}

//Print the results
System.out.println("---Path taken---");   
for (int i = 0; i< st.size(); i++) {
    System.out.println(st.pop);
    i++
}

除了语法错误外,你们能给我提供一些帮助吗?非常感谢。


你遇到了什么具体的错误? - templatetypedef
你能描述一下你遇到的问题吗?你认为哪些方面不正确? - Scott Hunter
我不确定我是否正确地执行了邻居检查,例如在迷宫中进行迭代。 - Copernikush
2
你具体出现了什么症状?你能举一个具体的例子来说明出了什么问题吗? - templatetypedef
5个回答

13

图片描述

我在此提交了一个类似的答案:C++迷宫解决算法

要有机会解决这个问题,你应该:

  • 创建一个Solve()例程并递归调用它:
    • 如果第1、2、3个...都正确,Solve已成功找到解决方案
    • 如果第1、2、3个...包含错误,则必须回溯并找到另一种方法
  • 您需要构建一个已访问位置的缓冲区以避免无限循环
    • 随着您进行移动,它需要跟踪它
    • 当我们遇到死路时,我们需要删除错误的移动
    • 我们可以通过烧入一个猜测并在错误时将其删除来实现上述功能

以下是解决方案的伪代码。

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;
 }

这是一个深度优先搜索算法。您可以在Baeldung上阅读更多相关信息。 - Flimtix

7

我认为你应该模块化你的程序 - 按照我的理解,你是在读取迷宫文件的同时尝试着解决它。

更好的方法是将程序分成两个不同的部分:

  1. 读入输入文件并创建包含所有数据的矩阵
  2. 从给定的矩阵解决迷宫问题

这样做可以帮助你单独构建和测试每个部分,这可能会导致更好、更可靠的程序。

使用一个简单的BFS来解决迷宫问题,类似于你最初提出的算法,即DFS


我认为原始算法是DFS,因为他使用了一个堆栈。话虽如此,我更喜欢BFS的解决方案。 - templatetypedef
@templatetypedef:您说得对,我已经编辑并修正了那个错误。谢谢。 - amit
我不知道那些都是什么意思...我们还没有学过那些东西。 - Copernikush
@Copernikush:这个答案的主要思路很简单:不要一边读取文件,一边尝试解决迷宫问题,而是先读取文件并从中创建一个包含所有数据的矩阵。完成这一步后,集中精力使用您的矩阵来解决迷宫问题。这种方法将帮助您测试程序的小部分,并确保每个部分都正常工作,因此更容易找到和修复任何错误。 - amit

1
正如amit所说,您应该先读取整个迷宫,并将其存储为二维数组。这让您无需逐行解决它即可查看整个迷宫。
由于您首先需要找到数组的大小,因此您应该将文本文件读入字符串列表中。
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);
}

列表的大小给出了行数,假设它总是一个网格,您可以使用split().length(计算空格+1)或计算任何一个字符串上的符号数量来获取列数。

存储地图数据最简单的方法是使用布尔值的二维数组。其中true表示墙壁,false表示空白空间。

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;
        }

    }

}

现在你已经把地图数据存储在数组中,遍历地图并进行选择就容易多了。你可以使用一个现成的算法(参见阿米特的答案),也可以自己设计一个。由于这是一份作业,你应该尝试思考自己的方案。

玩得开心。


0

我尝试使用DFS算法和一些Java面向对象的概念来实现这个。

在我的GitHub存储库上查看完整解决方案。

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
你需要将程序分成两个阶段。第一个是初始化阶段,在这里读取迷宫描述和玩家初始位置。之后,你就有了代表棋盘的数据结构。第二个阶段是实际游戏,其中应该有三个抽象:
  • 玩家状态。在你的情况下,它很简单,就是在棋盘上的实际位置。
  • 迷宫本身,即环境。它应该有函数告诉你是否访问了给定位置,标记你已经访问的位置,目标在哪里,下一个可达单元等等...
  • 逻辑,即搜索算法。
任何一个都可以在不更改其他内容的情况下进行更改。例如,您可能会被要求改善搜索算法,或者面临有多个目标的问题。从当前问题到稍微修改的问题的易于切换程度是程序设计的真正指标。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接