LeetCode 329 Longest Increasing Path in a Matrix (记忆化搜索)

来源:互联网 发布:godaddy域名被转走 编辑:程序博客网 时间:2024/05/22 13:36

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:

nums = [  [9,9,4],  [6,6,8],  [2,1,1]]

Return 4
The longest increasing path is [1, 2, 6, 9].

Example 2:

nums = [  [3,4,5],  [3,2,6],  [2,2,1]]

Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.


题目链接:https://leetcode.com/problems/longest-increasing-path-in-a-matrix/


题目分析:设dp[i][j]为到(i, j)这个位置时最长上升路径长度,击败了50%。。。
public class Solution {        int [][]dp;    int dx[] = {0, 0, 1, -1};    int dy[] = {1, -1, 0, 0};        int DFS (int x, int y, int n, int m, int[][] matrix) {        if (dp[x][y] != 0) {            return dp[x][y];        }        dp[x][y] = 1;        for (int i = 0; i < 4; i ++) {            int xx = x + dx[i];            int yy = y + dy[i];            if (xx >= 0 && xx < n && yy >= 0 && yy < m && matrix[xx][yy] < matrix[x][y]) {                dp[x][y] = Math.max(dp[x][y], DFS(xx, yy, n, m, matrix) + 1);            }           }        return dp[x][y];    }        public int longestIncreasingPath(int[][] matrix) {        int n = matrix.length;        if (n == 0) {            return 0;        }        int m = matrix[0].length;        dp = new int[n + 1][m + 1];        for (int i = 0; i < n; i ++) {            Arrays.fill(dp[i], 0);        }        int ans = 1;        for (int i = 0; i < n; i ++) {            for (int j = 0; j < m; j ++) {                ans = Math.max(ans, DFS(i, j, n, m, matrix));            }        }        return ans;    }}


0 0
原创粉丝点击