|
| 1 | +""" |
| 2 | +Given an integer matrix, find the length of the longest increasing path. |
| 3 | +
|
| 4 | +From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move |
| 5 | +outside of the boundary (i.e. wrap-around is not allowed). |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +
|
| 9 | +nums = [ |
| 10 | + [9,9,4], |
| 11 | + [6,6,8], |
| 12 | + [2,1,1] |
| 13 | +] |
| 14 | +Return 4 |
| 15 | +The longest increasing path is [1, 2, 6, 9]. |
| 16 | +
|
| 17 | +Example 2: |
| 18 | +
|
| 19 | +nums = [ |
| 20 | + [3,4,5], |
| 21 | + [3,2,6], |
| 22 | + [2,2,1] |
| 23 | +] |
| 24 | +Return 4 |
| 25 | +The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. |
| 26 | +""" |
| 27 | +__author__ = 'Daniel' |
| 28 | + |
| 29 | + |
| 30 | +class Solution(object): |
| 31 | + def __init__(self): |
| 32 | + self.cache = None |
| 33 | + self.dirs = ((-1, 0), (1, 0), (0, -1), (0, 1),) |
| 34 | + |
| 35 | + def longestIncreasingPath(self, matrix): |
| 36 | + """ |
| 37 | + dfs + cache |
| 38 | + :type matrix: List[List[int]] |
| 39 | + :rtype: int |
| 40 | + """ |
| 41 | + if not matrix: return 0 |
| 42 | + |
| 43 | + m, n = len(matrix), len(matrix[0]) |
| 44 | + self.cache = [[None for _ in xrange(n)] for _ in xrange(m)] |
| 45 | + gmax = 1 |
| 46 | + for i in xrange(m): |
| 47 | + for j in xrange(n): |
| 48 | + gmax = max(gmax, self.longest(matrix, i, j)) |
| 49 | + |
| 50 | + return gmax |
| 51 | + |
| 52 | + def longest(self, matrix, i, j): |
| 53 | + """ |
| 54 | + Strictly increasing, thus no need to have a visited matrix |
| 55 | + """ |
| 56 | + if not self.cache[i][j]: |
| 57 | + m, n = len(matrix), len(matrix[0]) |
| 58 | + maxa = 1 |
| 59 | + for d in self.dirs: |
| 60 | + I, J = i + d[0], j + d[1] |
| 61 | + if 0 <= I < m and 0 <= J < n and matrix[I][J] > matrix[i][j]: |
| 62 | + maxa = max(maxa, 1 + self.longest(matrix, I, J)) |
| 63 | + |
| 64 | + self.cache[i][j] = maxa |
| 65 | + |
| 66 | + return self.cache[i][j] |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + assert Solution().longestIncreasingPath([ |
| 71 | + [9, 9, 4], |
| 72 | + [6, 6, 8], |
| 73 | + [2, 1, 1] |
| 74 | + ]) == 4 |
0 commit comments