[leetcode/lintcode 题解] 蛇梯棋
2020-07-16 05:38
399 查看
在一块 N x N 的棋盘 board 上,从棋盘的左下角开始,每一行交替方向,按从 1 到 N*N 的数字给方格编号。例如,对于一块 6 x 6 大小的棋盘,可以编号如下:
玩家从棋盘上的方格 1 (总是在最后一行、第一列)开始出发。
每一次从方格 x 起始的移动都由以下部分组成:
-
你选择一个目标方块 S,它的编号是 x+1,x+2,x+3,x+4,x+5,或者 x+6,只要这个数字 <= N*N。
-
如果 S 有一个蛇或梯子,你就移动到那个蛇或梯子的目的地。否则,你会移动到 S。
在 r 行 c 列上的方格里有 “蛇” 或 “梯子”;如果 board[r][c] != -1,那个蛇或梯子的目的地将会是 board[r][c]。
注意,你每次移动最多只能爬过蛇或梯子一次:就算目的地是另一条蛇或梯子的起点,你也不会继续移动。
返回达到方格 N*N 所需的最少移动次数,如果不可能,则返回 -1。
- 2 <= board.length = board[0].length <= 20
- 2<=board.length=board[0].length<=20
- board[i][j] 介于 1和 N*N 之间或者等于 -1
- 编号为 1 的方格上没有蛇或梯子。
- 编号为 N*N 的方格上没有蛇或梯子。
在线评测地址: https://www.lintcode.com/problem/snakes-and-ladders/?utm_source=sc-csdn-fks
样例1:
输入:[[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]] 输出:4 解释: 首先,从方格 1 [第 5 行,第 0 列] 开始。 你决定移动到方格 2,并必须爬过梯子移动到到方格 15。 然后你决定移动到方格 17 [第 3 行,第 5 列],必须爬过蛇到方格 13。 然后你决定移动到方格 14,且必须通过梯子移动到方格 35。 然后你决定移动到方格 36, 游戏结束。 可以证明你需要至少 4 次移动才能到达第 N*N 个方格,所以答案是 4。
样例2
输入: [[2,2,-1],[2,2,2],[-1,2,2]] 输出: -1
【题解】
BFS即可
class Solution { public int snakesAndLadders(int[][] board) { int N = board.length; Map<Integer, Integer> dist = new HashMap(); dist.put(1, 0); Queue<Integer> queue = new LinkedList(); queue.add(1); while (!queue.isEmpty()) { int s = queue.remove(); if (s == N*N) return dist.get(s); for (int s2 = s+1; s2 <= Math.min(s+6, N*N); ++s2) { int rc = get(s2, N); int r = rc / N, c = rc % N; int s2Final = board[r][c] == -1 ? s2 : board[r][c]; if (!dist.containsKey(s2Final)) { dist.put(s2Final, dist.get(s) + 1); queue.add(s2Final); } } } return -1; } public int get(int s, int N) { // Given a square num s, return board coordinates (r, c) as r*N + c int quot = (s-1) / N; int rem = (s-1) % N; int row = N - 1 - quot; int col = row % 2 != N % 2 ? rem : N - 1 - rem; return row * N + col; } }
更多语言代码参见:https://www.jiuzhang.com/solution/snakes-and-ladders/?utm_source=sc-csdn-fks
相关文章推荐
- [leetcode/lintcode 题解] 尽量减少恶意软件的传播II
- lintcode/leetcode由易至难第2题:冒泡排序
- LeetCode 311 / LintCode 654 Sparse Matrix Multiplication
- LintCode题解之统计数字
- 排颜色问题——数组 leetcode lintcode
- lintcode/leetcode由易至难第20题:Integer Break
- lintcode/leetcode由易至难第21题:Encode and Decode TinyURL
- lintcode/leetcode由易至难第6题:Number Complement
- lintcode/leetcode由易至难第7题:Distribute Candies
- lintcode/leetcode由易至难第14题:Single Number
- lintcode/leetcode由易至难第3题:选择排序
- LeetCode 527 / LintCode 639 Word Abbreviation
- lintcode/leetcode由易至难第10题:Delete Node in a Linked List
- lintcode/leetcode由易至难第17题:Counting Bits
- Lintcode182 Delete Digits solution 题解
- lintcode/leetcode由易至难第15题:Merge Two Binary Trees
- LeetCode 269 / LintCode 892 Alien Dictionary
- lintcode/leetcode由易至难第11题:Same Tree
- Lintcode154 Regular Expression Matching solution 题解
- lintcode/leetcode由易至难第19题:Teemo Attacking