【Leetcode】562. Longest Line of Consecutive One in Matrix

题目地址:

https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/

给定一个 m × n m\times n m×n 0 − 1 0-1 01矩阵 A A A,求最长的连续出现的 1 1 1有多长,其可以是水平的、竖直的、对角线或者反对角线的。

f 1 [ i ] [ j ] f_1[i][j] f1[i][j]是以 ( i , j ) (i,j) (i,j)为水平结尾的最长水平连续 1 1 1的长度,水平的可以从左向右递推,则有 f 1 [ i ] [ j ] = { 0 , A [ i ] [ j ] = 0 1 + f 1 [ i ] [ j − 1 ] , A [ i ] [ j ] = 1 f_1[i][j]=\begin{cases}0, A[i][j]=0\\ 1+f_1[i][j-1], A[i][j]=1\end{cases} f1[i][j]={0,A[i][j]=01+f1[i][j1],A[i][j]=1其余可以类似递推。代码如下:

public class Solution {
    public int longestLine(int[][] mat) {
        int res = 0, m = mat.length, n = mat[0].length;
        int[][][] f = new int[4][m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 0) {
                    continue;
                }
                
                f[0][i][j] = j == 0 ? 1 : 1 + f[0][i][j - 1];
                f[1][i][j] = i == 0 ? 1 : 1 + f[1][i - 1][j];
                f[2][i][j] = i >= 1 && j >= 1 ? 1 + f[2][i - 1][j - 1] : 1;
                f[3][i][j] = i >= 1 && j < n - 1 ? 1 + f[3][i - 1][j + 1] : 1;
                // 更新答案
                for (int[][] g : f) {
                    res = Math.max(res, g[i][j]);
                }
            }
        }
        
        return res;
    }
}

时空复杂度 O ( m n ) O(mn) O(mn)

你可能感兴趣的:(LC,贪心,动态规划与记忆化搜索,leetcode,算法,动态规划)