用栈解决迷宫问题

迷宫问题是计算机科学中一个经典的问题,它可以通过使用栈来解决。在本文中,我们将使用Java语言来介绍如何使用栈来解决迷宫问题。

迷宫问题简介

迷宫问题是一个寻找从起点到终点的路径的问题,其中起点和终点被围在一个迷宫中的墙壁之间。迷宫由一个二维矩阵表示,其中0表示可以通过的路径,1表示墙壁。我们需要找到一条从起点到终点的路径,路径只能由相邻的可通过路径组成。

例如,给定以下迷宫:

1 0 0 0 0
1 1 1 1 0
0 0 0 0 0
1 1 1 1 1
0 0 0 0 1

我们需要找到一条从左上角到右下角的路径。

栈的使用

栈是一种后进先出(LIFO)的数据结构,它可以用来解决迷宫问题。我们可以使用栈来存储已经访问过的路径,以便在需要回溯时可以退回到之前的位置。每当我们探索一个新的路径时,我们将当前位置压入栈中,并将其标记为已访问。如果当前位置没有可探索的邻居,则我们将从栈中弹出一个位置并回溯到上一个位置。

代码示例

下面是使用Java语言实现栈解决迷宫问题的代码示例:

import java.util.Stack;

public class MazeSolver {
    private int[][] maze;
    private int[][] visited;
    private int startRow;
    private int startCol;
    private int endRow;
    private int endCol;
    private Stack<int[]> path;

    public MazeSolver(int[][] maze, int startRow, int startCol, int endRow, int endCol) {
        this.maze = maze;
        this.startRow = startRow;
        this.startCol = startCol;
        this.endRow = endRow;
        this.endCol = endCol;
        this.visited = new int[maze.length][maze[0].length];
        this.path = new Stack<>();
    }

    public boolean solve() {
        int[] start = {startRow, startCol};
        path.push(start);

        while (!path.isEmpty()) {
            int[] current = path.peek();
            int row = current[0];
            int col = current[1];
            visited[row][col] = 1;

            if (row == endRow && col == endCol) {
                return true;
            }

            if (isValidMove(row - 1, col)) {  // 上
                int[] next = {row - 1, col};
                path.push(next);
            } else if (isValidMove(row + 1, col)) {  // 下
                int[] next = {row + 1, col};
                path.push(next);
            } else if (isValidMove(row, col - 1)) {  // 左
                int[] next = {row, col - 1};
                path.push(next);
            } else if (isValidMove(row, col + 1)) {  // 右
                int[] next = {row, col + 1};
                path.push(next);
            } else {
                path.pop();
            }
        }

        return false;
    }

    private boolean isValidMove(int row, int col) {
        if (row >= 0 && row < maze.length && col >= 0 && col < maze[0].length && maze[row][col] == 0 && visited[row][col] == 0) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        int[][] maze = {
                {1, 0, 0, 0, 0},
                {1, 1, 1, 1, 0},
                {0, 0, 0, 0, 0},
                {1, 1, 1, 1, 1},
                {0, 0, 0, 0, 1}
        };
        int startRow = 0;
        int startCol = 0;
        int endRow = 4;
        int endCol = 4;

        MazeSolver solver = new MazeSolver(maze, startRow, startCol, endRow, endCol);
        boolean hasSolution = solver.solve();

        if (hasSolution) {
            System.out.println("迷宫有解,路径如下:");
            solver.path.forEach(point