[LeetCode] Longest Line of Consecutive One in Matrix

Description

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.

Example:

Input: mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
Output: 3

Solution

The basic idea is DP (Dynamic Programming), and we use 4 different number to record different types of consecutive ones.

dp0: the vertical consecutive ones

dp1: the horizontal consecutive ones

dp2: the diagonal consecutive ones

dp3: the anti-diagonal consecutive ones

Then, the only thing for us is to find the longest consecutive ones.

Code

class Solution {
public:
    int longestLine(vector<vector<int>>& mat) {
        int m = mat.size(), n = mat[0].size(), ans = 0;
        vector<vector<vector<int>>> dp(m + 2, vector<vector<int>>(n + 2, vector<int>(4, 0)));
        for(int i = 1; i <= m; i++) {
            for(int j = 1; j <= n; j++) {
                if(mat[i - 1][j - 1]) {
                    dp[i][j][0] = dp[i - 1][j][0] + 1;
                    dp[i][j][1] = dp[i][j - 1][1] + 1;
                    dp[i][j][2] = dp[i - 1][j - 1][2] + 1;
                    dp[i][j][3] = dp[i - 1][j + 1][3] + 1;
                    ans = max({ans, dp[i][j][0], dp[i][j][1], dp[i][j][2], dp[i][j][3]});
                }
            }
        }
        return ans;
    }
};

Optimized Space Solution

class Solution {
public:
    int longestLine(vector<vector<int>>& mat) {
        int m = mat.size(), n = mat[0].size();
        vector<vector<int>> dp(4, vector<int>(n + 2, 0));
        int ans = 0;
        for(int i = 1; i <= m; i++) {
            fill(dp[1].begin(), dp[1].end(), 0);
            int prev = dp[2][0];
            for(int j = 1; j <= n; j++) {
                int tmp = dp[2][j];
                if(mat[i - 1][j - 1] == 0) {
                    dp[0][j] = dp[1][j] = dp[2][j] = dp[3][j] = 0;
                }
                else {
                    dp[0][j] = dp[0][j] + 1;
                    dp[1][j] = dp[1][j - 1] + 1;
                    dp[2][j] = prev + 1;
                    dp[3][j] = dp[3][j + 1] + 1;
                    ans = max({ans, dp[0][j], dp[1][j], dp[2][j], dp[3][j]});
                }
                prev = tmp;
            }
        }
        return ans;
    }
};

Complexity

Time complexity: O(m * n)

Space complexity: O(m * n) -> O(n)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值