Talentd
FleetCode

562. Longest Line of Consecutive One in Matrix

Medium50.5% acceptance1 companyPremium elsewhere, free here

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.

Asked at 1 company

Hints open one at a time

Hint 1
One solution is to count ones in each direction separately and find the longest line. Don't you think it will take too much lines of code?
Hint 2
Is it possible to use some extra space to make the solution simple?
Hint 3
Can we use dynamic programming to make use of intermediate results?
Hint 4
Think of a 3D array which can be used to store the longest line obtained so far for each direction.
18:04
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[[0,1,1,0],[0,1,1,0],[0,0,0,1]]
Input
[[1,1,1,1],[0,1,1,0],[0,0,0,1]]
Your code is saved on this device.Solution