LeetCode Longest Increasing Path in a Matrix

太久沒有回來寫了。寒假的時候把題目都刷完,這次暑假剛剛開始就正好可以刷一刷。

這道題目是經典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


發佈了288 篇原創文章 · 獲贊 12 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章