★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-kjpnkhqs-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
On an N
xN
chessboard, a knight starts at the r
-th row and c
-th column and attempts to make exactly K
moves. The rows and columns are 0 indexed, so the top-left square is (0, 0)
, and the bottom-right square is (N-1, N-1)
.git
A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. github
Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.微信
The knight continues moving until it has made exactly K
moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving. dom
Example:spa
Input: 3, 2, 0, 0 Output: 0.0625 Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. From each of those positions, there are also two moves that will keep the knight on the board. The total probability the knight stays on the board is 0.0625.
Note:code
N
will be between 1 and 25.K
will be between 0 and 100.已知一個 N
xN
的國際象棋棋盤,棋盤的行號和列號都是從 0 開始。即最左上角的格子記爲 (0, 0)
,最右下角的記爲 (N-1, N-1)
。 orm
現有一個 「馬」(也譯做 「騎士」)位於 (r, c)
,並打算進行 K
次移動。 htm
以下圖所示,國際象棋的 「馬」 每一步先沿水平或垂直方向移動 2 個格子,而後向與之相垂直的方向再移動 1 個格子,共有 8 個可選的位置。blog
如今 「馬」 每一步都從可選的位置(包括棋盤外部的)中獨立隨機地選擇一個進行移動,直到移動了 K
次或跳到了棋盤外面。
求移動結束後,「馬」 仍留在棋盤上的機率。
示例:
輸入: 3, 2, 0, 0 輸出: 0.0625 解釋: 輸入的數據依次爲 N, K, r, c 第 1 步時,有且只有 2 種走法令 「馬」 能夠留在棋盤上(跳到(1,2)或(2,1))。對於以上的兩種狀況,各自在第2步均有且只有2種走法令 「馬」 仍然留在棋盤上。 因此 「馬」 在結束後仍在棋盤上的機率爲 0.0625。
注意:
N
的取值範圍爲 [1, 25]K
的取值範圍爲 [0, 100]1 class Solution { 2 var dirs:[[Int]] = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] 3 func knightProbability(_ N: Int, _ K: Int, _ r: Int, _ c: Int) -> Double { 4 var memo:[[[Double]]] = [[[Double]]](repeating:[[Double]](repeating:[Double](repeating:0.0,count:N),count:N),count:K + 1) 5 return helper(&memo, N, K, r, c) / pow(8.0, Double(K)) 6 } 7 8 func helper(_ memo:inout [[[Double]]],_ N:Int,_ k:Int,_ r:Int,_ c:Int) -> Double 9 { 10 if k == 0 {return 1.0} 11 if memo[k][r][c] != 0.0 {return memo[k][r][c]} 12 for dir in dirs 13 { 14 var x:Int = r + dir[0] 15 var y:Int = c + dir[1] 16 if x < 0 || x >= N || y < 0 || y >= N 17 { 18 continue 19 } 20 memo[k][r][c] += helper(&memo, N, k - 1, x, y) 21 } 22 return memo[k][r][c] 23 } 24 }