Skip to content

562. Longest Line of Consecutive One in Matrix 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int longestLine(vector<vector<int>>& mat) {
    const int m = mat.size();
    const int n = mat[0].size();
    int ans = 0;
    // dp[i][j][0] := horizontal
    // dp[i][j][1] := vertical
    // dp[i][j][2] := diagonal
    // dp[i][j][3] := anti-diagonal
    vector<vector<vector<int>>> dp(m, vector<vector<int>>(n, vector<int>(4)));

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (mat[i][j] == 1) {
          dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;
          dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;
          dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;
          dp[i][j][3] = (i > 0 && j < n - 1) ? dp[i - 1][j + 1][3] + 1 : 1;
          ans = max(ans, ranges::max(dp[i][j]));
        }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
  public int longestLine(int[][] mat) {
    final int m = mat.length;
    final int n = mat[0].length;
    int ans = 0;
    // dp[i][j][0] := horizontal
    // dp[i][j][1] := vertical
    // dp[i][j][2] := diagonal
    // dp[i][j][3] := anti-diagonal
    int[][][] dp = new int[m][n][4];

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (mat[i][j] == 1) {
          dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;
          dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;
          dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;
          dp[i][j][3] = (i > 0 && j < n - 1) ? dp[i - 1][j + 1][3] + 1 : 1;
          for (int k = 0; k < 4; ++k)
            ans = Math.max(ans, dp[i][j][k]);
        }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def longestLine(self, mat: list[list[int]]) -> int:
    m = len(mat)
    n = len(mat[0])
    ans = 0
    # dp[i][j][0] := horizontal
    # dp[i][j][1] := vertical
    # dp[i][j][2] := diagonal
    # dp[i][j][3] := anti-diagonal
    dp = [[[0] * 4 for j in range(n)] for _ in range(m)]

    for i in range(m):
      for j in range(n):
        if mat[i][j] == 1:
          dp[i][j][0] = dp[i][j - 1][0] + 1 if j > 0 else 1
          dp[i][j][1] = dp[i - 1][j][1] + 1 if i > 0 else 1
          dp[i][j][2] = dp[i - 1][j - 1][2] + 1 if i > 0 and j > 0 else 1
          dp[i][j][3] = dp[i - 1][j + 1][3] + 1 if i > 0 and j < n - 1 else 1
          ans = max(ans, max(dp[i][j]))

    return ans