[LeetCode] Longest Line of Consecutive One in Matrix

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.

  • Time : O(nm)
  • Space : O(m)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int longestLine(vector<vector<int>>& mat) {
int ma = 0, m = mat[0].size();
vector<int> ho(m,0), ve(m,0), dia(m,0), anti(m,0);
for(auto& row : mat) {
for(int i = 0, j = m - 1; i < m; i++, j--) {
if(i == 0) ho[i] = row[i];
else ho[i] = row[i] ? ho[i-1] + 1 : 0;

ve[i] = row[i] ? ve[i] + 1 : 0;

if(j) dia[j] = row[j] ? dia[j-1] + 1 : 0;
else dia[j] = row[j];

if(i != m - 1) anti[i] = row[i] ? anti[i + 1] + 1 : 0;
else anti[i] = row[i];

ma = max({ma, ho[i], ve[i], dia[j], anti[i]});
}
}
return ma;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/12/PS/LeetCode/longest-line-of-consecutive-one-in-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.