Python recursive

  • 0

    Nothing to explain, the code should have explained itself very well.

    def knightProbability(self, N, K, r, c):
        directions = ((2,1),(2,-1),(-2,1),(-2,-1),(1,2),(1,-2),(-1,2),(-1,-2))
        def search(row, col, k, cache={}):
            if (row, col, k) in cache: return cache[(row, col, k)]
            if k == 0: return 1.
            p = 0
            for (i, j) in map(lambda (x, y): (x + row, y + col), directions):
                if 0 <= i < N and 0 <= j < N:
                    p += 1/8. * search(i, j, k - 1)
            return cache.setdefault((row, col, k), p)
        return search(r, c, K)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.