562. Longest Line of Consecutive One in Matrix

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了562. Longest Line of Consecutive One in Matrix相关的知识,希望对你有一定的参考价值。

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


Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical, diagonal or anti-diagonal.
Example:?
Input:
[[0,1,1,0],
 [0,1,1,0],
 [0,0,0,1]]
Output: 3




class Solution {
    public int longestLine(int[][] M) {
        int res = 0;
        if(M == null || M.length == 0) return res;
        int m = M.length;
        int n = M[0].length;
        int[][][] dp = new int[m][n][4];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(M[i][j] == 1){
                    // horizontal 
                    dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;
                    // vertical
                    dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;
                    // diag
                    dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;
                    // rever dia
                    dp[i][j][3] = (i > 0 && j + 1 < n) ? dp[i - 1][j + 1][3] + 1 : 1; // j + 1 < n 
                    res = Math.max(res, Math.max(Math.max(dp[i][j][0], dp[i][j][1]), Math.max(dp[i][j][2], dp[i][j][3])));
                }
            }
        }
        return res;  
    }
}

 

以上是关于562. Longest Line of Consecutive One in Matrix的主要内容,如果未能解决你的问题,请参考以下文章

leetcode562- Longest Line of Consecutive One in Matrix- medium

LeetCode 562. Longest Line of Consecutive One in Matrix(在矩阵中最长的连续1)$

[LeetCode] Longest Line of Consecutive One in Matrix 矩阵中最长的连续1

understanding of Pipe line & Timing Logic

LeetCode Number of Longest Increasing Subsequence

673. Number of Longest Increasing Subsequence