This is a classic Dynamic Programming problem. And u haven't mentioned the entire algorithm which is as follows:
To construct the auxiliary array we have to do the following:
First copy the first row and first column as it is from M[][] to S[][]
And for the remaining entries as u mentioned do the following:
If M[i][j] is 1 then
S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
Else /*If M[i][j] is 0*/
S[i][j] = 0
Find the maximum entry in S[][] and use it to construct the maximum size square submatrix
What does this relation signify?
To find the maximum square, we need to find the minimum extension of 1s in different directions and add 1 to it to form the length of square ending at present case.
so as for your case s[][] would be:
0 1 1 0 1
1 1 0 1 0
0 1 1 1 0
1 1 2 2 0
1 2 2 3 1
0 0 0 0 0
If we just take minimum of these i.e S[i][j-1], S[i-1][j]
, it takes care of left and top direction.However, we also need to make sure that there are 1's in top left corner of perspective square.
S[i-1][j-1], by definition, contains a max square at position i-1, j-1, whose top left corner ,puts an upper limit on how up and left we can get. So, we need to consider that as well.
Hope this helps!