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;

否则,方向++;


}

}


  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值