Java-栈方法实现迷宫问题

import java.util.Stack;

public class Solution {
    public final int M = 6;
    public final int N = 8;
    //8*10  M+2,N+2
    public int[][] maze = {
            {1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
            {1, 0, 1, 1, 1, 0, 1, 1, 1, 1},
            {1, 1, 0, 1, 0, 1, 1, 1, 1, 1},
            {1, 0, 1, 0, 0, 0, 0, 0, 1, 1},
            {1, 0, 1, 1, 1, 0, 1, 1, 1, 1},
            {1, 1, 0, 0, 1, 1, 0, 0, 0, 1},
            {1, 0, 1, 1, 0, 0, 1, 1, 0, 1},
            {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
    };
    //8个移动方向的增量值,顺时针,东、东南、南......
    public Direction directions[] = {
            new Direction(0, 1),    //东
            new Direction(1, 1),
            new Direction(1, 0),
            new Direction(1, -1),
            new Direction(0, -1),
            new Direction(-1, -1),
            new Direction(-1, 0),
            new Direction(-1, 1)
    };

    public boolean isExit() {
        Stack s = new Stack();
        int x, y, d;
        int i, j;
        //入口进站
        s.push( new Item(1, 1, 0));
        while (!s.empty()) {
            Item item = (Item) s.pop();
            x = item.x;
            y = item.y;
            d = item.d;
            while (d < 8) {
                i = x + directions[d].x;
                j = y + directions[d].y;
                if (maze[i][j] == 0) {
                    s.push(new Item(x, y, d));
                    x = i;
                    y = j;
                    maze[x][y] = 3;//标记,已经走过
                    if (x == M && y == N) return true;
                    else {
                        d = 0;
                    }
                } else {
                    d++;
                }
            }

        }
        return false;

    }


}


class Direction {
    int x, y;

    public Direction(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

class Item {
    int x, y, d;

    public Item(int x, int y, int d) {
        this.x = x;
        this.y = y;
        this.d = d;
    }
}

先贴代码,懒得上思路了,简单分析一下:

迷宫m行n列maze[m][n],0表示通,1表示不通。从一个点可以向8个方向探路,为了处理边角情况,迷宫的四周全部加一行一列,最后为maze[m+2][n+2]。

思路:

栈初始化,

将入口点push入栈,

while(栈不为空)

{

栈顶元素出站;

while(方向<8){

如果可走,入栈,求新点坐标,并赋值给当前点,如果等于出口,返回成果。否则方向=0;

否则,方向++;


}

}


你可能感兴趣的:(算法与数据结构)