设置访问室的迷宫解决回溯算法问题

时间:2011-03-21 14:33:49

标签: java algorithm maze backtracking

如果有人能用我的房间搜索算法帮助我,我会寻求 我正在尝试为迷宫解决实施回溯算法。我被困在我应该记住我已经去过的房间的地方 迷宫由房间组成,每个房间有4个侧面 - 北,东,南和西。每个房间通过打开一扇通向所需侧面的房间与下一个房间相连,即room1.createNorth(roomName)在北面创建一个新房间,新房间有一个南门,可以连接到第一个房间,就像我在Room类中看到的那样。

这是我的破碎房间类,代表迷宫中的每个房间。我删除了南,西,东方向,这与我处理北方的方法相同。

public class Room {

    private String name;
    private Room north;
    private Room east;
    private Room west;
    private Room south;
    private boolean isExit = false;
    private Maze maze;

    /**
     * @return name room
     */
    public String getName() {
        return this.name;
    }

    /**
     * Sets room name
     * 
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Gets northern room if any
     * 
     * @return pointer to northern room if any, otherwise <code>null</code>
     */
    public Room getNorth() {
        return this.north;
    }

    /**
     * Sets the door to the next room to the north in that room and in the other
     * room sets southern door as connecting back to that room
     * 
     * @param otherRoom
     */
    public void setNorth(Room otherRoom) {
        this.north = otherRoom;
        otherRoom.south = this;
    }

    /**
     * creates a new room to the north and connects back to this room
     * 
     * @param name
     *            of the room
     * @return created room
     */
    public Room createNorth(String name) {
        Room otherRoom = null;

        // create new room in that direction ONLY if there is no room yet
        if (this.getNorth() == null) { // get northern direction, if it's null,
                                        // then it's okay to create there
            otherRoom = new Room(); // create!
            this.setNorth(otherRoom); // set the door
            otherRoom.setName(name); // set the name

        } else { // there is a room in that direction, so don't create a new
                    // room and drop a warning
            System.out.println("There is already a room in northern direction");
        }

        return otherRoom;
    }

    /**
     * Asdf
     * 
     * @return maze
     */
    public Maze getMaze() {
        return this.maze;
    }

    /**
     * Set maze
     * 
     * @param maze
     */
    public void setMaze(Maze maze) {
        this.maze = maze;
    }

    /**
     * @param roomName path to this room must be found
     */
    public void findPathTo(String roomName) {
        Room soughtRoom = this.getMaze().getEntry();

        while (!(soughtRoom.getName().equalsIgnoreCase(roomName))) {

//          here should be also a method such as setRoomAsVisited()

            if (this.getWest() != null) {
                soughtRoom = this.getWest();
                this.getMaze().getPaths().push(soughtRoom);
            }
            else if (this.getNorth() != null) {
                soughtRoom = this.getNorth();
                this.getMaze().getPaths().push(soughtRoom);
            }
            else if (this.getEast() != null) {
                soughtRoom = this.getEast();
                this.getMaze().getPaths().push(soughtRoom);
            }
            else if (this.getSouth() != null) {
                soughtRoom = this.getSouth();
                this.getMaze().getPaths().push(soughtRoom);
            }
            else {
                if (this.getMaze().getPaths().isEmpty()) {
                    break; // no more path for backtracking, exit (no solution found)
                }
                // dead end, go back!
                soughtRoom = this.getMaze().getPaths().pop();
            }
            System.out.println(this.getMaze().getPaths().toString());
        }


    }

    @Override
    public String toString() {
        return "Room name is " + this.getName();
    }
}

迷宫看起来像这样:http://i.stack.imgur.com/2KePs.jpg其中S是起点

我的迷宫课程

public class Maze {

    Room room;

/**
 * helper collection path stack for findPathTo() method
 */
private Stack<Room> paths = new Stack<Room>();

/**
 * @return path for exit
 */
public Stack<Room> getPaths() {
    return this.paths;
}

    /**
     * Singleton method for first room in the maze which is entry room
     * 
     * @return room if no room is created then creates new, otherwise returns
     *         already created room
     */
    public Room getEntry() {
        if (this.room == null) {
            this.room = new Room();
            return this.room;
        }
        return this.room;
    }
}

这是我的主要课程     公共课主要{

    public static void main(String[] args) {

        Maze maze = new Maze();
        maze.getEntry().setName("A4"); // set first room's name A4
        // labyrinth creation
        maze.getEntry().createEast("B4").createNorth("B3").createWest("A3");
        maze.getEntry().getEast().getNorth().createNorth("B2").createWest("A2")
                .createNorth("A1");
        maze.getEntry().getEast().getNorth().getNorth().createNorth("B1");
        maze.getEntry().getEast().getNorth().getNorth().createEast("C2")
                .createNorth("C1").createEast("D1");
        maze.getEntry().getEast().createEast("C4").createEast("D4");
        maze.getEntry().getEast().getEast().createNorth("C3").createEast("D3")
                .createNorth("D2").setExit(true);

        System.out.println("=====Test findPathTo method======");
        maze.getEntry().setMaze(maze); // set maze instance to our entrance room
        maze.getEntry().findPathTo("B4");

        System.out.println("=====End of testing findPathTo method======");

    }

}

问题出在我的findPathTo(roomName)方法中,该方法找到了到房间的路线。 如果我进入房间D4,那么我的算法只从“A4”向东移动一次到“B4”房间,在那里它只是无限循环而且堆栈只是在房间“B4”处增长。为什么它没有前进到例如下一个房间“B3”或“C4”?

编辑:这是工作代码

public void findPathTo(String roomName) {

        Room soughtRoom = this.getMaze().getEntry();

        while (!(soughtRoom.getName().equalsIgnoreCase(roomName))) {

            if (soughtRoom.getWest() != null && soughtRoom.getWest().isVisited != true) {
                this.getMaze().getPaths().push(soughtRoom);
                soughtRoom = soughtRoom.getWest();
                soughtRoom.isVisited = true;

            }
            else if (soughtRoom.getNorth() != null && soughtRoom.getNorth().isVisited != true) {
                this.getMaze().getPaths().push(soughtRoom);
                soughtRoom = soughtRoom.getNorth();
                soughtRoom.isVisited = true;

            }
            else if (soughtRoom.getEast() != null && soughtRoom.getEast().isVisited != true) {
                this.getMaze().getPaths().push(soughtRoom);
                soughtRoom = soughtRoom.getEast();
                soughtRoom.isVisited = true;

            }
            else if (soughtRoom.getSouth() != null && soughtRoom.getSouth().isVisited != true) {
                this.getMaze().getPaths().push(soughtRoom);
                soughtRoom = soughtRoom.getSouth();
                soughtRoom.isVisited = true;

            }
            else {
                if (this.getMaze().getPaths().isEmpty()) {
                    System.out.println("No solutions found :(");
                    break; // no more path for backtracking, exit (no solution found)
                }
                // dead end, go back!
                soughtRoom = this.getMaze().getPaths().pop();
            }
            System.out.println("Path rooms: " + this.getMaze().getPaths().toString());
        }
    }

3 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。

一种方法是在您跟踪和回溯继续进行设置/取消设置的每个房间对象中保留一个“isVisited”布尔标志。这意味着你只能单线程搜索你的迷宫(这可能或不重要)。

另一种方法是保留一个你比较的访问房间列表(这里的优点是,将一个新房间“推”到列表上应该相对容易,如果你使用调用栈就会自动弹出它通过这个清单)。

您还可以使用空间的每个搜索哈希表到isVisible,这允许(可能)比搜索列表更快的查找,允许多线程(如“多个线程可以搜索迷宫”,不是“多个线程可以参与相同的搜索”)。

我可能还有一些我没有想过的事情,但这三件事应该非常直接地实施。

答案 1 :(得分:0)

快速且高度未经优化的方法:

对于每个访问过的会议室,请存储可能的路线(例如,设置enum DirectionSet<Direction>)并删除您来自的路线以及您的方向从前一个房间拿走了。因此,从A4移动到B4,您将从A4移除EAST,从B4移除WEST。如果你必须追溯,只需展开堆栈,直到找到一个方向未访问的房间(可能的方向列表不为空),然后尝试下一个。如果此时堆栈变空,则在没有找到目标空间的情况下尝试了所有可能性。

正如我所说,这是非常不优化的,但它应该有用。

答案 2 :(得分:0)

一些意见:

您的代码缺少您正在使用的某些功能。您的迷宫类中没有getPaths()方法。如果您在线发布代码,请尝试确保它易于编译和测试。在你的情况下,我不得不猜测,getPaths()返回某种堆栈,你试图在其上存储可能被探索的路径,但是没有办法确定它实际上做了什么。

在发布之前还尝试简化代码。你的迷宫相当复杂,人们必须画它,看看你构造的迷宫是否与图片上的迷宫相匹配。尝试使用更简单的迷宫(可能是2或3个房间)重现问题。同样简化通常会给出许多关于问题可能出现的提示。当你简化时,问题会突然消失。这告诉你很多关于实际的错误。

关于您的代码可能出现的问题的一些想法: 在每个方向,您将seekRoom设置为该方向的那个。我假设seekRoom是您目前搜索的房间。然后你把那个房间推到堆栈上。但是对于回溯,您需要在每个分支处存储所有将您带回以前状态的信息。如果您首先设置当前房间然后按下它,则先前状态的信息将丢失。反过来试试看看会发生什么。