添加 problem 329

This commit is contained in:
YDZ
2019-12-30 20:59:38 +08:00
parent 4e41ed08a9
commit 448a61349c
3 changed files with 151 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
package leetcode
import (
"math"
)
func longestIncreasingPath(matrix [][]int) int {
cache, res := make([][]int, len(matrix)), 0
for i := 0; i < len(cache); i++ {
cache[i] = make([]int, len(matrix[0]))
}
for i, v := range matrix {
for j := range v {
searchPath(matrix, cache, math.MinInt64, i, j)
res = max(res, cache[i][j])
}
}
return res
}
func isInIntBoard(board [][]int, x, y int) bool {
return x >= 0 && x < len(board) && y >= 0 && y < len(board[0])
}
func searchPath(board, cache [][]int, lastNum, x, y int) int {
if board[x][y] <= lastNum {
return 0
}
if cache[x][y] > 0 {
return cache[x][y]
}
count := 1
for i := 0; i < 4; i++ {
nx := x + dir[i][0]
ny := y + dir[i][1]
if isInIntBoard(board, nx, ny) {
count = max(count, searchPath(board, cache, board[x][y], nx, ny)+1)
}
}
cache[x][y] = count
return count
}

View File

@@ -0,0 +1,67 @@
package leetcode
import (
"fmt"
"testing"
)
type question329 struct {
para329
ans329
}
// para 是参数
// one 代表第一个参数
type para329 struct {
matrix [][]int
}
// ans 是答案
// one 代表第一个答案
type ans329 struct {
one int
}
func Test_Problem329(t *testing.T) {
qs := []question329{
question329{
para329{[][]int{[]int{1}}},
ans329{1},
},
question329{
para329{[][]int{[]int{}}},
ans329{0},
},
question329{
para329{[][]int{[]int{9, 9, 4}, []int{6, 6, 8}, []int{2, 1, 1}}},
ans329{4},
},
question329{
para329{[][]int{[]int{3, 4, 5}, []int{3, 2, 6}, []int{2, 2, 1}}},
ans329{4},
},
question329{
para329{[][]int{[]int{1, 5, 9}, []int{10, 11, 13}, []int{12, 13, 15}}},
ans329{5},
},
question329{
para329{[][]int{[]int{1, 5, 7}, []int{11, 12, 13}, []int{12, 13, 15}}},
ans329{5},
},
}
fmt.Printf("------------------------Leetcode Problem 329------------------------\n")
for _, q := range qs {
_, p := q.ans329, q.para329
fmt.Printf("【input】:%v 【output】:%v\n", p, longestIncreasingPath(p.matrix))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,42 @@
# [329. Longest Increasing Path in a Matrix](https://leetcode.com/problems/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).
**Example 1:**
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
**Example 2:**
Input: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
## 题目大意
给定一个整数矩阵,找出最长递增路径的长度。对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
## 解题思路
- 给出一个矩阵,要求在这个矩阵中找到一个最长递增的路径。路径有上下左右 4 个方向。
- 这一题解题思路很明显,用 DFS 即可。在提交完第一版以后会发现 TLE因为题目给出了一个非常大的矩阵搜索次数太多。所以需要用到记忆化把曾经搜索过的最大长度缓存起来增加了记忆化以后再次提交 AC。