所以现在没有人做题用深度优先了是么,都是起手dp了? 而且这道题用的三维的dp真的有点子难
class Solution(object):
def knightProbability(self, n, k, row, column):
"""
:type n: int
:type k: int
:type row: int
:type column: int
:rtype: float
普通回溯,不过要算概率
不行啊 还是会超时,30步电脑都要烧熟了,要不用dp
"""
direction=[[-2,+1],[-1,+2],[+1,+2],[+2,+1],[+2,-1],[+1,-2],[-1,-2],[-2,-1]]
ans=[0]
def DFS(deepth,i,j):
if i>=0 and i<n and j>=0 and j<n:
if deepth==k:
ans[0]+=1
else:
for step in direction:
DFS(deepth+1,i+step[0],j+step[1])
DFS(0,row,column)
return float(ans[0])/(8**k)
把步数也当成了一个维度,其实本来是能想出来的:
一开始的思路:DFS超时,马上去想dp,但是dp的话只能想到按照位置dp而不是按照步数去dp所以思路陷住了,还有就是状态转移方程一旦列出来其实就可以明显的看出来到底怎么dp了
1.当steps==0时,对于所有[i][j]在棋盘上有棋dp[steps][i][j]=1
2.当steps!=0时,若[i][j]不在棋盘上则dp[steps][i][j]=0
3.对于一般的steps和i,j
class Solution(object):
def knightProbability(self, n, k, row, column):
"""
:type n: int
:type k: int
:type row: int
:type column: int
:rtype: float
"""
dp=[[[0]*n for i in range(n)] for j in range(k+1)]
for steps in range(k+1):#从状态转移方程看,每一步都是上一步的函数所以最外层用步数来迭代非常完美
for i in range(n):
for j in range(n):
if steps==0:
dp[steps][i][j]=1
else:
for di,dj in((-2, -1), (-2, 1), (2, -1), (2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2)):
last_i,last_j=i+di,j+dj#到达[steps][i][j]前的坐标
if last_i<n and last_i>=0 and last_j<n and last_j>=0:
dp[steps][i][j]+=float(1)/8*dp[steps-1][last_i][last_j]
return dp[k][row][column]