DFS:使用Dictionary来存储访问状态VS.排列

时间:2017-10-01 18:06:39

标签: python arrays dictionary matrix dfs

考虑到起始位置是r,c,我计算在K步之后停留N个N棋盘的概率。这是我的代码:

def knightProbability(self, N, K, r, c):
    # dfs.
    answer = 0
    dp = [[[-1] * N]*N] * (K+1)
    # dfs with memoization.
    self.dic = {}
    return self.dfs(N, K, r, c, dp) # Starting at r, c, what's the probability of staying on board after k moves.



def dfs(self, N, k, r, c, dp):
    offsets = [(-1, -2), (-1, 2), (-2, -1), (-2, 1), (1, -2), (1, 2), (2, -1), (2, 1)]
    answer = 0.0

    if k == 0:
        return 1.0

    '''if dp[k][r][c] >= 0:
        return dp[k][r][c]'''
    if str(k) + ":" + str(r) + ":" + str(c) in self.dic:
        return self.dic[str(k) + ":" + str(r) + ":" + str(c)]

    for offset in offsets:
        new_r = r + offset[0]
        new_c = c + offset[1]
        if new_r > -1 and new_r < N and new_c > -1 and new_c < N:
            answer += self.dfs(N, k-1, new_r, new_c, dp) * 1.0 / 8 # with k-1 steps, what's the probability?
    '''dp[k][r][c] = answer'''
    self.dic[str(k) + ":" + str(r) + ":" + str(c)] = answer
    return answer

这是一个简单的dfs。当我使用字典来存储和检索我现在正在做的访问状态(k,r,c)时,它可以工作。但是,如果我使用k by N by N数组来存储和检索它们,我得不到正确的答案。有什么想法吗?注释部分是我正在讨论的数组部分的存储/检索,它应该与当前代码做同样的事情。

0 个答案:

没有答案