算法分析课每周练习 Longest Increasing Path in a Matrix

来源:互联网 发布:网络诋毁企业 编辑:程序博客网 时间:2024/06/05 02:09

题目

Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

分析

有点像找单词的游戏,忘记叫什么了

class Solution(object):    def longestIncreasingPath(self, matrix):        """        :type matrix: List[List[int]]        :rtype: int        """        if not matrix: return 0        m, n = len(matrix), len(matrix[0])        dis = [[0 for j in xrange(n)] for i in xrange(m)]        return max([self.dfs(i, j, m, n, matrix, dis) for j in xrange(n) for i in xrange(m)])     def dfs(self, x, y, m, n, matrix, dis):        if dis[x][y]: return dis[x][y]        for dx, dy in ([(1, 0), (-1, 0), (0, 1), (0, -1)]):            nx, ny = x + dx, y + dy            if nx >= 0 and nx < m and ny >= 0 and ny < n and matrix[x][y] < matrix[nx][ny]:                dis[x][y] = max(dis[x][y], self.dfs(nx, ny, m, n, matrix, dis))        dis[x][y] += 1        return dis[x][y]


原创粉丝点击