# Dynamic programming algorithm to find largest triangle in binary square matrix where elements equal “1”

I'm struck how to find DP recurrence for:

You are given a binary square matrix M of size nxn. We define a (p,q, l)-triangle of M, where p >= 1, q >= 1, L >= 1, p+L >= n+1, and q+L >= n+1, as the set of elements M[i, j] satisfying p =< i < p+L, q =< j < q+L, and i+ j < p+q+L. Design an algorithm to find the largest (p,q, l)-triangle of M (“largest” means l is maximized) such that all its elements are “1”

EDIT: I added the original problem as requested:

solution:

I think I need to check first if:

element equal 1,

if so, check the element to its left, element in its top and element diagonally if equals "1"

if so increment the result,

but not sure how to put this into recurrence.

• Suppose p=q=1, L=2k. Suppose also that there is a (1,1,2k)-triangle. Draw it and think about what happens when you decompose it into a square of side length k and two new triangles. Next step is to generalize for odd lengths and general (p,q). – VashTheStampede Dec 21 '20 at 19:05
• The condition $p+L\ge n+1$ is somewhat misleading since the largest index for the index $i$ in $M[i,j]$ is $n$. Did you mean $p+L=n+1$? – John L. Dec 22 '20 at 5:00
• Can you add a reference to the original problem? Even if it is not in English, it is great to see the original version. I can then write code to check my answer. – John L. Dec 22 '20 at 5:05
• I don't think @VashTheStampede's suggestion will lead to a simple, fast DP algorithm. I suggest: Ask yourself what triangles must exist "locally" if there is a triangle of size $L$ with bottom-rightmost point at $(i,j)$. Using this directly would enable an $O(n^4)$-time algorithm, but that can be sped up to $O(n^2)$ by representing this information in a "compressed" way: If you know there is a size-$L$ triangle with bottom-right corner at $(i,j)$, you also know there is a size-$(L-1)$ triangle there, etc. – j_random_hacker Dec 23 '20 at 1:19
• @j_random_hacker my idea is quadratic with the right precomputation. In fact, if expressed as top-down dp it can be done in O(n^2) without any precomp :) I think I also catch your solution and indeed it needs some precomputation (on longest column/diagonal of 1s). If I am wrong I would like to read an answer once the OP has solved the problem! – VashTheStampede Dec 25 '20 at 8:48