LeetCode 0562. Longest Line of Consecutive One in Matrix Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0562. Longest Line of Consecutive One in Matrix

Description

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 1:

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

Example 2:

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

 

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • mat[i][j] is either 0 or 1.

Solutions

Solution 1: Dynamic Programming

We define f[i][j][k] to represent the length of the longest consecutive 1s ending at (i, j) in direction k. The value range of k is 0, 1, 2, 3, representing horizontal, vertical, diagonal, and anti-diagonal directions, respectively.

We can also use four 2D arrays to represent the length of the longest consecutive 1s in the four directions.

We traverse the matrix, and when we encounter 1, we update the value of f[i][j][k]. For each position (i, j), we only need to update the values in its four directions. Then we update the answer.

The time complexity is O(m × n), and the space complexity is O(m × n), where m and n are the number of rows and columns in the matrix, respectively.

PythonJavaC++Go
class Solution: def longestLine(self, mat: List[List[int]]) -> int: m, n = len(mat), len(mat[0]) a = [[0] * (n + 2) for _ in range(m + 2)] b = [[0] * (n + 2) for _ in range(m + 2)] c = [[0] * (n + 2) for _ in range(m + 2)] d = [[0] * (n + 2) for _ in range(m + 2)] ans = 0 for i in range(1, m + 1): for j in range(1, n + 1): if mat[i - 1][j - 1]: a[i][j] = a[i - 1][j] + 1 b[i][j] = b[i][j - 1] + 1 c[i][j] = c[i - 1][j - 1] + 1 d[i][j] = d[i - 1][j + 1] + 1 ans = max(ans, a[i][j], b[i][j], c[i][j], d[i][j]) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !