LeetCode #562 - Longest Line of Consecutive One in Matrix

题目描述:

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

Hint: The number of elements in the given matrix will not exceed 10,000.

class Solution {
public:
    int longestLine(vector<vector<int>>& M) {
        if(M.size()==0||M[0].size()==0) return 0;
        int m=M.size();
        int n=M[0].size();
        int result=0;
        //dp的第三维表示直线延伸的四个方向,k=0表示水平,k=1表示垂直,k=2表示对角线,k=3表示斜对角线
        vector<vector<vector<int>>> dp(m,vector<vector<int>>(n,vector<int>(4,0)));
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(M[i][j]==0) continue;
                else for(int k=0;k<4;k++) dp[i][j][k]=1;
                if(i>0) dp[i][j][0]+=dp[i-1][j][0];
                if(j>0) dp[i][j][1]+=dp[i][j-1][1];
                if(i>0&&j>0) dp[i][j][2]+=dp[i-1][j-1][2];
                if(i>0&&j<n-1) dp[i][j][3]+=dp[i-1][j+1][3];
                for(int k=0;k<4;k++) result=max(result,dp[i][j][k]);
            }
        }
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值