太久没有回来写了。寒假的时候把题目都刷完,这次暑假刚刚开始就正好可以刷一刷。
这道题目是经典dp题目,记得poj上面就有。
Description:
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).
大概就是说给一个矩阵,然后找一个最长连续上升或者下降序列。求这个序列的长度。连续的定义为矩阵中有相邻边。
直接记忆化搜索,每次搜索相邻边,如果已有记忆则读取记忆,否则相邻边+1与当前比,取大。
class Solution(object):
def Solution(self):
self.dir = [[1,0], [-1,0], [0,1], [0,-1]]
return
def longestIncreasingPath(self, matrix):
self.dir = [[1,0], [-1,0], [0,1], [0,-1]]
self.n = len(matrix)
self.m = len(matrix[0])
self.step = [ [-1 for j in range(self.m)] for i in range(self.n)]
self.matrix = matrix
max_step = 1
for i in range(self.n):
for j in range(self.m):
if self.step[i][j] == -1:
max_step = max(max_step, self.dfs(i,j))
return max_step
def dfs(self, cur_x, cur_y):
if self.step[cur_x][cur_y] > 0:
return self.step[cur_x][cur_y]
self.step[cur_x][cur_y] = 1
for i in range(4):
next_x = cur_x + self.dir[i][0]
next_y = cur_y + self.dir[i][1]
if not self.valid(next_x, next_y):
continue
if self.matrix[cur_x][cur_y] > self.matrix[next_x][next_y]:
self.step[cur_x][cur_y] = max(self.step[cur_x][cur_y], self.dfs(next_x, next_y) + 1)
return self.step[cur_x][cur_y]
def valid(self, x, y):
if x < 0 or x >= self.n:
return False
if y < 0 or y >= self.m:
return False
return True