Given a square matrix of 0's and 1's, calculate the size of the largest plus formed by 1's.

For example, for the matrix below, we have highlighted the largest plus of ones having size 17.

 
Largest Plus in Matrix
 

Practice this problem

 
We start by creating four auxiliary matrices left[][], right[][], top[][], bottom[][], where left[j][j], right[i][j], top[i][j], and bottom[i][j] store the maximum number of consecutive 1's present at the left, right, top and bottom of cell (i, j) including cell (i, j), respectively by using dynamic programming:

if grid[i][j] == 1
    left[i][j] = left[i][j – 1] + 1
 
if grid[i][j] == 1
    top[i][j] = top[i – 1][j] + 1
 
if grid[i][j] == 1
    bottom[i][j] = bottom[i + 1][j] + 1
 
if grid[i][j] == 1
    right[i][j] = right[i][j + 1] + 1

After calculating the above matrices, find cell (i, j) that has maximum value in each direction (by considering the minimum of left[i][j], right[i][j], top[i][j], bottom[i][j]). The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

The largest plus of 1’s has a size of 17

Java


Download  Run Code

Output:

The largest plus of 1’s has a size of 17

Python


Download  Run Code

Output:

The largest plus of 1’s has a size of 17

The time complexity of the proposed solution is O(N2) for an N × N matrix. The auxiliary space required by the program is O(N2).
 

 
Author: Aditya Goel