其他分享
首页 > 其他分享> > [Google] LeetCode 562 Longest Line of Consecutive One in Matrix

[Google] LeetCode 562 Longest Line of Consecutive One in Matrix

作者:互联网

Given an m x n binary matrix mat, return the length of the longest line of consecutive one in the matrix.

The line could be horizontal, vertical, diagonal, or anti-diagonal.

Solution

我们需要统计行、列以及对角线中最长的连续的 \(1\) 的数量。

直接考虑 \(dp[i][j][k]\),其中利用 \(k\) 来表示行、列、对角线和反对角线。

点击查看代码
class Solution {
private:
    int ans=0;
public:
    int longestLine(vector<vector<int>>& mat) {
        int r = mat.size(), c = mat[0].size();
        vector<vector<vector<int>>> dp(r, vector<vector<int>>(c, vector<int>(4,0)) ); 
        
        for(int i=0;i<r;i++){
            for(int j=0;j<c;j++){
                if(mat[i][j]==0) continue;
                for(int k=0;k<4;k++){
                    dp[i][j][k]=1;
                }
                if(i>0)dp[i][j][0]=1+dp[i-1][j][0];
                if(j>0)dp[i][j][1]=1+dp[i][j-1][1];
                if(i>0 && j>0)dp[i][j][2]=1+dp[i-1][j-1][2];
                if(i>0 && j<c-1){
                    dp[i][j][3]=1+dp[i-1][j+1][3];
                }
                ans=max(ans,max(dp[i][j][0],max(dp[i][j][1], max(dp[i][j][2], dp[i][j][3]))));
            }
        }
        return ans;
    }
};







标签:Google,Matrix,int,562,vector,对角线,line,dp,mat
来源: https://www.cnblogs.com/xinyu04/p/16651849.html