day71(1.30)——leetcode面试经典150

909. 蛇梯棋

909. 蛇梯棋

太破防了啊啊啊啊,我的索引++,没有--,就直接超出内存限制,真没招了,找了好久错误,太粗心了啊啊啊啊啊

题目:

题解:

java 复制代码
class Solution {
    public int snakesAndLadders(int[][] board) {
        int n = board.length;
        int target = n*n;
        //值映射坐标
        Map<Integer, int[]> map = new HashMap<>();
        int flag = 1;
        int num = 1;
        //我真服了,这个i没--,我还以为是变量名触发了什么呢
        for(int i=n-1;i>=0;i--) {
            if(flag == 1) {
                for(int j=0;j<n;j++) {
                    map.put(num++, new int[]{i,j});
                }
            }
            else {
                for(int j=n-1;j>=0;j--) {
                    map.put(num++, new int[]{i,j});
                }
            }
            flag = -flag;
        }
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(1);
        //移动次数
        int step=0;
        boolean[] visited = new boolean[target + 1]; // 1-indexed
        visited[1]=true;
        while(queue.size()>0) {
            int size = queue.size();
            step++;

            for(int i=0;i<size;i++) {
                int t = queue.poll();
                int[] l = map.get(t);
                int x = l[0];
                int y = l[1];

                for(int j=t+1;j<=Math.min(target, t+6); j++) {
                    
                     int fin = j;
                    int[] li = map.get(fin);
                    int r = li[0], c = li[1];
                    
                    if (board[r][c] != -1) {
                        fin = board[r][c];
                    }
                    
                    // 如果是终点,直接返回
                    if (fin == target) {
                        return step;
                    }

                    if(visited[fin]==false) {
                        // 标记并入队
                        visited[fin] = true;
                        queue.offer(fin);
                    }
                }
            }
        }
        return -1;
    }
}
相关推荐
Mahir085 小时前
Spring 循环依赖深度解密:从问题本质到三级缓存源码级解析
java·后端·spring·缓存·面试·循环依赖·三级缓存
心中有国也有家6 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
绝知此事7 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
碧海银沙音频科技研究院7 小时前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
csdn_aspnet7 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
kyriewen10 小时前
面试官让我查各部门工资最高的员工,我用AI三秒写出窗口函数,他愣了
后端·mysql·面试
罗超驿10 小时前
18.事务的隔离性和隔离级别:MySQL面试高频考点全解析
数据库·mysql·面试
m0_6294947310 小时前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
壹号用户10 小时前
用队列实现栈
数据结构·算法