Finding longest line of 1s in a matrix in JavaScript

Suppose, we have a binary matrix (an array of arrays that contains only 0 or 1) like this:

const arr = [
   [0,1,1,0],
   [0,1,1,0],
   [0,0,0,1]
];

We need to write a JavaScript function that takes a binary matrix as input and finds the longest line of consecutive ones. The line can be horizontal, vertical, diagonal, or anti-diagonal.

For the above array, the output should be 3 because the longest line starts from arr[0][1] and spans diagonally to arr[2][3].

Approach

We'll use dynamic programming with a 3D array where each cell stores the length of consecutive 1s in four directions:

  • Index 0: Horizontal (left to right)
  • Index 1: Vertical (top to bottom)
  • Index 2: Diagonal (top-left to bottom-right)
  • Index 3: Anti-diagonal (top-right to bottom-left)

Example

const arr = [
   [0,1,1,0],
   [0,1,1,0],
   [0,0,0,1]
];

const longestLine = (arr = []) => {
   if(!arr.length){
      return 0;
   }
   
   let rows = arr.length, cols = arr[0].length;
   let res = 0;
   
   // Initialize 3D DP array
   const dp = Array(rows).fill(null).map(() => 
      Array(cols).fill(null).map(() => Array(4).fill(0))
   );
   
   for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
         if (arr[i][j] == 1) {
            // Horizontal: extend from left
            dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;
            
            // Vertical: extend from top
            dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;
            
            // Diagonal: extend from top-left
            dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;
            
            // Anti-diagonal: extend from top-right
            dp[i][j][3] = (i > 0 && j < cols - 1) ? dp[i - 1][j + 1][3] + 1 : 1;
            
            // Update maximum length found
            res = Math.max(res, Math.max(dp[i][j][0], dp[i][j][1]));
            res = Math.max(res, Math.max(dp[i][j][2], dp[i][j][3]));
         }
      }
   }
   
   return res;
};

console.log(longestLine(arr));
3

How It Works

For each cell containing 1, we calculate the length of consecutive 1s ending at that position in all four directions. The algorithm builds up these lengths incrementally, using previously computed values to avoid redundant calculations.

Time Complexity

The time complexity is O(m × n) where m and n are the matrix dimensions, as we visit each cell once and perform constant time operations.

Conclusion

This dynamic programming solution efficiently finds the longest line of consecutive 1s in any direction within a binary matrix. The approach scales well for larger matrices while maintaining optimal time complexity.

Updated on: 2026-03-15T23:19:00+05:30

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements