前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Java-栈方法实现迷宫问题

Java-栈方法实现迷宫问题

作者头像
leehao
发布2025-02-11 13:09:36
发布2025-02-11 13:09:36
5700
代码可运行
举报
文章被收录于专栏:leehao
运行总次数:0
代码可运行
代码语言:javascript
代码运行次数:0
复制
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;

否则,方向++;

}

}

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-02-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档