寻找迷宫的最短路径

3

这个类使用图形来打印迷宫。程序将运行3次。在第一次之后,我保存了一个步数数组,用来计算角色经过一个点的次数。然后将此数组写入文件。在下一次运行之前,我需要打开文件。我需要使用文件的内容来“学习”哪些地方不应该去试(即避免死路,找到最快的完成路径)。

我有一个名为 hasBadBranch() 的方法,我希望对于所有具有“步数”>1的分支(交叉口的北、南、东、西部分支),返回 true。当我在我的 solve() 方法中添加 hasBadBranch 条件时,我得到了数组索引越界,并且角色无法正确通过迷宫。如果有人看到我的逻辑上的任何缺陷,我将非常感谢反馈。谢谢。

public class Maze extends JFrame {

    private static final int MAX_WIDTH = 255;
    private static final int MAX_HEIGHT = 255;

    private char[][] maze = new char[MAX_HEIGHT][MAX_WIDTH];
    private int[][] steps = new int[MAX_HEIGHT][MAX_WIDTH];

    private Random random = new Random();
    private JPanel mazePanel = new JPanel();
    private int width = 0;
    private int height = 0;
    private boolean step = false;

    private boolean timerFired = false;
    private Timer timer;
    private final int TIMER_DELAY = 20;

    private final int SPRITE_WIDTH = 25;
    private final int SPRITE_HEIGHT = 25;

    private BufferedImage mazeImage;
    private ImageIcon ground = new ImageIcon("sprites/ground.png");
    private ImageIcon wall1 = new ImageIcon("sprites/cactus.png");
    private ImageIcon wall2 = new ImageIcon("sprites/rock.png");
    private ImageIcon finish = new ImageIcon("sprites/well.png");
    private ImageIcon south1 = new ImageIcon("sprites/cowboy-forward-1.png");
    private ImageIcon south2 = new ImageIcon("sprites/cowboy-forward-2.png");
    private ImageIcon north1 = new ImageIcon("sprites/cowboy-back-1.png");
    private ImageIcon north2 = new ImageIcon("sprites/cowboy-back-2.png");
    private ImageIcon west1 = new ImageIcon("sprites/cowboy-left-1.png");
    private ImageIcon west2 = new ImageIcon("sprites/cowboy-left-2.png");
    private ImageIcon east1 = new ImageIcon("sprites/cowboy-right-1.png");
    private ImageIcon east2 = new ImageIcon("sprites/cowboy-right-2.png");

    private long startTime;
    private long currentTime;

    private static final int MAX_TIME = 500000;

    /**
     * Constructor for class Maze. Opens a text file containing the maze, then
     * attempts to solve it.
     *
     * @param fname String value containing the filename of the maze to open.
     */
    //Notes to user: 
    //delete steps.txt BEFORE testing begins and AFTER third run of program
    //use appropriate file paths
    public Maze(String fname) throws FileNotFoundException, IOException {
        openMaze(fname);
        mazeImage = printMaze();

        readInFile();

        timer = new Timer(TIMER_DELAY, new TimerHandler());     // setup a Timer to slow the animation down.
        timer.start();

        addWindowListener(new WindowHandler());     // listen for window event windowClosing

        setTitle("Cowboy Maze");
        setSize(width * SPRITE_WIDTH + 10, height * SPRITE_HEIGHT + 30);
        setVisible(true);

        add(mazePanel);
        setContentPane(mazePanel);

        solveMaze();
    }

    public void readInFile() throws FileNotFoundException, IOException {
        //Note to user: adjust file path accordingly
        File stepsFile = new File("C:\\Users\\Ashley Bertrand\\Desktop\\Data Structures\\Lab6\\mazeStartSourceMazesGraphics\\steps.txt");

        if (stepsFile.isFile()) {
            Scanner scanner = new Scanner(stepsFile);
            int lineCount = 0;
            while (scanner.hasNextLine()) {
                String[] currentLine = scanner.nextLine().trim().split("\\s+");
                for (int i = 0; i < currentLine.length; i++) {
                    steps[lineCount][i] = Integer.parseInt(currentLine[i]);
                }
                lineCount++;
            }

            System.out.println("Contents of steps.txt:");
            for (int m = 0; m < width; m++) {
                for (int n = 0; n < height; n++) {
                    System.out.print(steps[m][n]);
                }
                System.out.println();
            }
            System.out.println();
        } else {
            System.out.println("Running first trial so steps.txt does not exist");
        }
    }

    /**
     * Called from the operating system. If no command line arguments are
     * supplied, the method displays an error message and exits. Otherwise, a
     * new instance of Maze() is created with the supplied filename from the
     * command line.
     *
     * @param args[] Command line arguments, the first of which should be the
     * filename to open.
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        int runny = 1;
        if (args.length > 0) {
            new Maze(args[0]);
        } else {
            System.out.println();
            System.out.println("Usage: java Maze <filename>.");
            System.out.println("Maximum Maze size:" + MAX_WIDTH + " x " + MAX_HEIGHT + ".");
            System.out.println();
            System.exit(1);
        }
    }

    /**
     * Finds the starting location and passes it to the recursive algorithm
     * solve(x, y, facing). The starting location should be the only '.' on the
     * outer wall of the maze.
     */
    public void solveMaze() throws FileNotFoundException {
        boolean startFound = false;
        if (!startFound) {
            for (int i = 0; i < width; i++) {       // look for the starting location on the top and bottom walls of the Maze.
                if (maze[0][i] == '.') {
                    maze[0][i] = 'S';
                    steps[0][i]++;
                    preSolve(i, 0, "south");
                    startFound = true;
                } else if (maze[height - 1][i] == '.') {
                    maze[height - 1][i] = 'S';
                    steps[height - 1][i]++;
                    preSolve(i, height - 1, "north");
                    startFound = true;
                }
            }
        }
        if (!startFound) {
            for (int i = 0; i < height; i++) {      // look for the starting location on the left and right walls of the Maze.
                if (maze[i][0] == '.') {
                    maze[i][0] = 'S';
                    steps[i][0]++;
                    preSolve(0, i, "east");
                    startFound = true;
                } else if (maze[i][width - 1] == '.') {
                    maze[i][width - 1] = 'S';
                    steps[i][width - 1]++;
                    preSolve(width - 1, i, "west");
                    startFound = true;
                }
            }
        }
        if (!startFound) {
            System.out.println("Start not found!");
        }
    }

    public void preSolve(int x, int y, String facing) throws FileNotFoundException {
        Scanner input = new Scanner(System.in);
        System.out.println("Press 1 to start");
        input.nextLine();
        startTime = System.currentTimeMillis();
        solve(x, y, facing);
    }

    /**
     * Recursive algorithm to solve a Maze. Places an X at locations already
     * visited. This algorithm is very inefficient, it follows the right hand
     * wall and will never find the end if the path leads it in a circle.
     *
     * @param x int value of the current X location in the Maze.
     * @param y int value of the current Y location in the Maze.
     * @param facing String value holding one of four cardinal directions
     * determined by the current direction facing.
     */
    private void solve(int x, int y, String facing) throws FileNotFoundException {
        Graphics2D g2 = (Graphics2D) mazePanel.getGraphics(); //don't mess with the next 

        while (!timerFired) {   // wait for the timer.
            try {
                Thread.sleep(10);
            } catch (Exception e) {
            }
        }
        timerFired = false;
        currentTime = System.currentTimeMillis();
        if ((currentTime - startTime) > MAX_TIME) {
            closingMethod();
        }

        if (maze[y][x] != 'F') {  //this is if it doesn't find the finish on a turn.........
            g2.drawImage(mazeImage, null, 0, 0);
            g2.drawImage(printGuy(facing), x * SPRITE_WIDTH, y * SPRITE_HEIGHT, null, null);
            mazePanel.setSize(width * SPRITE_WIDTH + 10, height * SPRITE_HEIGHT + 30);
            maze[y][x] = 'X';   // mark this spot as visited. This is how you can keep track of where you've been. 

            if (facing.equals("east")) {
                if (maze[y + 1][x] != '#' && maze[y + 1][x] != '%' && maze[y + 1][x] != 'S' && !hasBadBranch(y+1, x)) {
                    steps[y + 1][x]++;
                    solve(x, y + 1, "south");
                } else if (maze[y][x + 1] != '#' && maze[y][x + 1] != '%' && maze[y][x + 1] != 'S' && !hasBadBranch(y, x+1)) {
                    steps[y][x + 1]++;
                    solve(x + 1, y, "east");
                } else {
                    solve(x, y, "north");
                }
            } else if (facing.equals("west")) {
                if (maze[y - 1][x] != '#' && maze[y - 1][x] != '%' && maze[y - 1][x] != 'S' && !hasBadBranch(y-1, x)) {
                    steps[y - 1][x]++;
                    solve(x, y - 1, "north");
                } else if (maze[y][x - 1] != '#' && maze[y][x - 1] != '%' && maze[y][x - 1] != 'S'&& !hasBadBranch(y, x-1)) {
                    steps[y][x - 1]++;
                    solve(x - 1, y, "west");
                } else {
                    solve(x, y, "south");
                }
            } else if (facing.equals("south")) {
                if (maze[y][x - 1] != '#' && maze[y][x - 1] != '%' && maze[y][x - 1] != 'S' && !hasBadBranch(y, x-1)) {
                    steps[y][x - 1]++;
                    solve(x - 1, y, "west");
                } else if (maze[y + 1][x] != '#' && maze[y + 1][x] != '%' && maze[y + 1][x] != 'S' && !hasBadBranch(y+1, x)) {
                    steps[y + 1][x]++;
                    solve(x, y + 1, "south");
                } else {
                    solve(x, y, "east");
                }
            } else if (facing.equals("north")) {
                if (maze[y][x + 1] != '#' && maze[y][x + 1] != '%' && maze[y][x + 1] != 'S' && !hasBadBranch(y, x+1)) {
                    steps[y][x + 1]++;
                    solve(x + 1, y, "east");
                } else if (maze[y - 1][x] != '#' && maze[y - 1][x] != '%' && maze[y - 1][x] != 'S' && !hasBadBranch(y-1, x)) {
                    steps[y - 1][x]++;
                    solve(x, y - 1, "north");
                } else {
                    solve(x, y, "west");
                }
            }

        } else {
            writeToFile();
            System.out.println("Found the finish!");

            currentTime = System.currentTimeMillis();
            long endTime = currentTime - startTime;
            long finalTime = endTime / 1000;
            System.out.println("Final Time = " + finalTime);

        }
    }

    public boolean hasBadBranch(int y, int x) {
        //9999 will be used to tell character not to take that branch
        if (steps[y][x] > 1) {
            if (steps[y + 1][x] > 1) {
                steps[y + 1][x] = 9999;
                return true;    //south
            }
            if (steps[y - 1][x] > 1) {
                steps[y - 1][x] = 9999;
                return true;    //north
            }
            if (steps[y][x + 1] > 1) {
                steps[y][x + 1] = 9999;
                return true;    //east
            }
            if (steps[y][x - 1] > 1) {
                steps[y][x - 1] = 9999;
                return true;    //west
            }
        }
        return false;
    }

    /**
     * Opens a text file containing a maze and stores the data in the 2D char
     * array maze[][].
     *
     * @param fname String value containing the file name of the maze to open.
     */
    public void openMaze(String fname) {
        String in = "";
        int i = 0;
        try {
            Scanner sc = new Scanner(new File(fname));
            while (sc.hasNext()) {
                in = sc.nextLine();
                in = trimWhitespace(in);
                if (in.length() <= MAX_WIDTH && i < MAX_HEIGHT) {
                    for (int j = 0; j < in.length(); j++) {
                        if (in.charAt(j) == '#') {      // if this spot is a wall, randomize the wall peice to display
                            if (random.nextInt(2) == 0) {
                                maze[i][j] = '#';
                            } else {
                                maze[i][j] = '%';
                            }
                        } else {
                            maze[i][j] = in.charAt(j);
                        }
                    }
                } else {
                    System.out.println("Maximum maze size exceeded: (" + MAX_WIDTH + " x " + MAX_HEIGHT + ")!");
                    System.exit(1);
                }
                i++;
            }
            width = in.length();
            height = i;
            System.out.println("(" + width + " x " + height + ") maze opened.");
            System.out.println();
            sc.close();
        } catch (FileNotFoundException e) {
            System.err.println("File not found: " + e);
        }
    }

    /**
     * Removes white space from the supplied string and returns the trimmed
     * String.
     *
     * @param s String value to strip white space from.
     * @return String stripped of white space.
     */
    public String trimWhitespace(String s) {
        String newString = "";
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != ' ') {
                newString += s.charAt(i);
            }
        }
        return newString;
    }

    /**
     * Returns the sprite facing the direction supplied.
     *
     * @param facing String value containing 1 of 4 cardinal directions to make
     * the sprite face.
     * @return Image of the sprite facing the proper direction.
     */
    private Image printGuy(String facing) {
        if (facing.equals("south")) {  // draw sprite facing south
            if (step) {
                step = false;
                return south1.getImage();
            } else {
                step = true;
                return south2.getImage();
            }
        } else if (facing.equals("north")) {  // draw sprite facing north
            if (step) {
                step = false;
                return north1.getImage();
            } else {
                step = true;
                return north2.getImage();
            }
        } else if (facing.equals("east")) {  // draw sprite facing east
            if (step) {
                step = false;
                return east1.getImage();
            } else {
                step = true;
                return east2.getImage();
            }
        } else if (facing.equals("west")) {  // draw sprite facing west
            if (step) {
                step = false;
                return west1.getImage();
            } else {
                step = true;
                return west2.getImage();
            }
        }
        return null;
    }

    /**
     * Prints the Maze using sprites.
     *
     * @return BufferedImage rendition of the maze.
     */
    public BufferedImage printMaze() {
        BufferedImage mi = new BufferedImage(width * SPRITE_WIDTH, height * SPRITE_HEIGHT, BufferedImage.TYPE_INT_ARGB);
        Graphics g2 = mi.createGraphics();

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (maze[i][j] == '#') {    // draw wall
                    g2.drawImage(wall1.getImage(), j * SPRITE_WIDTH, i * SPRITE_HEIGHT, null, null);
                } else if (maze[i][j] == '%') {   // draw wall
                    g2.drawImage(wall2.getImage(), j * SPRITE_WIDTH, i * SPRITE_HEIGHT, null, null);
                } else if (maze[i][j] == '.' || maze[i][j] == 'X') {  // draw ground
                    g2.drawImage(ground.getImage(), j * SPRITE_WIDTH, i * SPRITE_HEIGHT, null, null);
                } else if (maze[i][j] == 'F') {   // draw finish
                    g2.drawImage(finish.getImage(), j * SPRITE_WIDTH, i * SPRITE_HEIGHT, null, null);
                }
            }
        }
        return mi;
    }

    public void writeToFile() throws FileNotFoundException {
        PrintWriter printWriter = new PrintWriter("steps.txt");
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                printWriter.print(steps[i][j] + " ");
            }
            printWriter.println();
        }
        printWriter.close();
    }

    public void closingMethod() {
        long endTime = currentTime - startTime;
        long finalTime = endTime / 100;
        System.exit(0);
    }

    private class TimerHandler implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            timerFired = true;
        }
    }

    private class WindowHandler extends WindowAdapter {

        public void windowClosing(WindowEvent e) {
            removeAll();
            closingMethod();
            System.exit(0);
        }
    }

}

1
你为什么决定用这种方式解决迷宫呢?这样做不会给你最优的答案。你应该使用广度优先搜索算法。 - Haozhun
我的教授给了我们这个通用的迷宫解决方案大纲,要求我们重复尝试三次,并保存所学,这样第三次尝试时就可以通过直接路径解决它。 - CS student
我理解广度优先搜索的工作原理,但是你如何将其应用于这样的迷宫呢? @Haozhun - CS student
@CSstudent 嘿,你有什么问题吗?你知道需要保存什么到文件中吗?我看到了一个 openMaze 方法,但是似乎你还没有保存任何东西? - almightyGOSU
我正在将迷宫保存到文件中,并展示第一次运行时我的移动。在第二次运行时,我将打开该文件,但如何使用该信息来减少到达终点的不必要路径?@Gosu - CS student
显示剩余4条评论
1个回答

0

基本上你所做的是使用固定探索规则(右手)使用DFS解决迷宫问题。你应该保存的信息是你踏上一个方块的次数。当你遇到死路时,你将返回交叉口尝试另一条分支。

因此,在第二次解决问题时,当你发现一个得分>1的交叉口时,你应该修改探索规则,避免那些得分>1的分支(1表示你从未回来过==之前的解决路径,2(或更多)表示你在死路(或几个死路)后回来了)。希望这有意义。


BFS会更快地找到最短解吧? - M. Shaw
感谢@softwarenewbie7331。我正在尝试编写一个方法,检查交叉点并查看其任何分支是否> 1,如果是,则返回true。我的代码似乎有问题(数组越界,字符不能正确通过迷宫)。您能否看出我的逻辑中的缺陷? public boolean badIntersection(int y, int x) { if (steps[y][x] > 1) { if (steps[y + 1][x] > 1) { steps[y + 1][x] = 9999; //标记不应走的路径 return true; //向南 } ... } } - CS student
在我的解决方法中,我添加了以下内容: if (facing.equals("east")) { if (maze[y + 1][x] != '#' && maze[y + 1][x] != '%' && !isBadIntersection(y+1, x)) { steps[y + 1][x]++; solve(x, y + 1, "south"); } else if (maze[y][x + 1] != '#' && maze[y][x + 1] != '%' && !isBadIntersection(y, x+1)) { steps[y][x + 1]++; solve(x + 1, y, "east"); } else { solve(x, y, "north"); } ... } - CS student
你应该把这个问题放在问题区,这样其他人就可以阅读和帮助了。越界显然是因为你需要检查右边界和底部边界。不确定第二个注释代码在做什么。@M.Shaw 我猜他被迫使用他的教授想要的东西(类似dfs)。 - softwarenewbie7331

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