Leetcode - Longest Increasing Path in a Matrix

My code:

public class Solution {
    private int row = 0;
    private int col = 0;
    public int longestIncreasingPath(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        row = matrix.length;
        col = matrix[0].length;
        int max = 1;
        int[][] cache = new int[row][col];
        
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (cache[i][j] != 0) {
                    max = Math.max(max, cache[i][j]);
                    continue;
                }
                else {
                    cache[i][j] = helper(matrix, cache, i, j);
                    max = Math.max(max, cache[i][j]);
                }
            }
        }
        
        return max;
    }
    
    private int helper(int[][] matrix, int[][] cache, int i, int j) {
        if (cache[i][j] != 0) {
            return cache[i][j];
        }
        else {
            int sum = 0;
            if (inBound(i + 1, j) && matrix[i][j] < matrix[i + 1][j]) {
                sum = Math.max(sum, helper(matrix, cache, i + 1, j));
            }
            if (inBound(i - 1, j) && matrix[i][j] < matrix[i - 1][j]) {
                sum = Math.max(sum, helper(matrix, cache, i - 1, j));
            }
            if (inBound(i, j + 1) && matrix[i][j] < matrix[i][j + 1]) {
                sum = Math.max(sum, helper(matrix, cache, i, j + 1));
            }
            if (inBound(i, j - 1) && matrix[i][j] < matrix[i][j - 1]) {
                sum = Math.max(sum, helper(matrix, cache, i, j - 1));
            }
            
            sum += 1;
            cache[i][j] = sum;
            return sum;
        }
    }
    
    private boolean inBound(int i, int j) {
        if (i >= 0 && i < row && j >= 0 && j < col) {
            return true;
        }
        else {
            return false;
        }
    }
}

这道题目并不是很难。
dfs + cache 就可以解决。
速度有点慢。看了答案。发现实现方法跟我差不多。他跑15ms, 我跑 39ms. 也差不多。估计实现细节上差了点。

reference:
https://discuss.leetcode.com/topic/34835/15ms-concise-java-solution/8

Anyway, Good luck, Richardo! — 08/28/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/a97ad671456d#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞