Leetcode #562: Longest Line of Consecutive One in Matrix
In this guide, we solve Leetcode #562 Longest Line of Consecutive One in Matrix in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Dynamic Programming, Matrix
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: mat = [[0,1,1,0],[0,1,1,0],[0,0,0,1]]
Output: 3
Python Solution
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
Complexity
The time complexity is , and the space complexity is , where and are the number of rows and columns in the matrix, respectively. The space complexity is , where and are the number of rows and columns in the matrix, respectively.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.