Longest Line of Consecutive One in Matrix — LeetCode 562 Python Solution

MediumLeetCode PremiumArrayDynamic ProgrammingMatrix
Problem
#562
Reading time
3 min

The problem

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

Python solution

Python
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

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n), where m and n are the number of rows and columns in the matrix, respectively auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 562. Longest Line of Consecutive One in Matrix is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 562. Longest Line of Consecutive One in Matrix?
LeetCode 562. Longest Line of Consecutive One in Matrix is rated Medium on LeetCode.
What is the time complexity of LeetCode 562. Longest Line of Consecutive One in Matrix?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 562. Longest Line of Consecutive One in Matrix?
The Python solution on this page uses O(m \times n), where m and n are the number of rows and columns in the matrix, respectively auxiliary space.
What topics does LeetCode 562. Longest Line of Consecutive One in Matrix cover?
LeetCode 562. Longest Line of Consecutive One in Matrix is tagged Array, Dynamic Programming and Matrix on LeetCode.
Is LeetCode 562. Longest Line of Consecutive One in Matrix a premium problem?
Yes. LeetCode 562. Longest Line of Consecutive One in Matrix is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview