2019年3月6日 980. Unique Paths III

看描述就知道是一道搜索题,不过判断条件有点多,需要全部位置都踩一遍,相当于一笔画?

代码其实有点潦草了,因为额外的有点工作的事情,最近时间可能不多了。

class Solution(object):

    def checkPath(self, grid, n, m):
        for i in range(n):
            for j in range(m):
                if grid[i][j] == 0:
                    return 0
        return 1

    def findPath(self, grid, i, j, n, m, path):
        mypath = copy.deepcopy(path)
        mygrid = copy.deepcopy(grid)

        mypath.append((i, j))
        if grid[i][j] == 2:
            #print(mypath)
            return self.checkPath(grid, n, m)

        mygrid[i][j] = -1
        #self.printGrid(grid, n, m)
        ret = 0

        for vi, vj in ((0,1), (1,0), (-1,0), (0,-1)):
            x = i + vi
            y = j + vj
            if x >= 0 and y >= 0 and x < n and y < m:
                if mygrid[x][y] in (0, 2):
                    ret += self.findPath(mygrid, x, y, n, m, mypath)

        return ret


    def uniquePathsIII(self, grid):
        ret = None
        n = len(grid)
        m = len(grid[0])
        for i in range(n):
            for j in range(m):
                if grid[i][j] == 1:
                    ret = self.findPath(grid, i, j, n, m, [])
                    break
            if ret is not None:
                break
        return ret
上一篇:linux环境变量详解


下一篇:CSV数据存取