Largest Plus Formed by All Ones in a Binary Square Matrix
Last Updated : 16 Jun, 2026
Given an n × n binary matrix mat[][] consisting of 0s and 1s, find the size of the largest ‘+’ shape that can be formed using only 1s. If no ‘+’ can be formed, return 0.
Note: A ‘+’ shape is formed by a central cell from which four arms extend in the up, down, left, and right directions, while staying within the matrix boundaries. The size of the ‘+’ shape is defined as the total number of cells that make up the structure, including the center cell and all the cells in its four arms.
Examples:
Input: mat[][] = [[0, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 1, 0]] Output: 5 Explanation: Largest ‘+’ would be formed by highlighted part of size 5.
[Naive Approach] Check Every Cell as Center - O(n ^ 3) Time and O(1) Space
Treat every cell containing 1 as the center of a '+' and expand simultaneously in all four directions while the cells contain 1s. The largest valid expansion determines the size of the '+' centered at that cell. Repeat this for all cells and keep track of the maximum size found.
Output
5
[Expected Approach] Using Dynamic Programming - O(n ^ 2) Time and O(n ^ 2) Space
For each cell, precompute the number of consecutive 1s extending left, right, up, and down (including the cell itself). The maximum possible arm length of a '+' centered at a cell is the minimum of these four values. Compute this for every cell and return the largest '+' size found.
Step By Step Implementation:
We use four auxiliary matrices: left[][], right[][], top[][] and bottom[][].
left[i][j] stores the number of consecutive 1s to the left of cell (i, j), including the cell itself.
right[i][j] stores the number of consecutive 1s to the right of cell (i, j), including the cell itself.
top[i][j] stores the number of consecutive 1s above cell (i, j), including the cell itself.
bottom[i][j] stores the number of consecutive 1s below cell (i, j), including the cell itself.
For every cell, the maximum possible arm length of a '+' centered at that cell is the minimum of left[i][j], right[i][j], top[i][j], and bottom[i][j]. We compute this value for all cells and use the largest one to determine the size of the largest '+'.