Largest rectangular sub matrix with the same number

后端 未结 4 1050
醉梦人生
醉梦人生 2020-12-12 17:36

I am trying to come up with a dynamic programming algorithm that finds the largest sub matrix within a matrix that consists of the same number:

example:



        
4条回答
  •  情话喂你
    2020-12-12 18:07

    A dynamic solution:

    Define a new matrix A wich will store in A[i,j] two values: the width and the height of the largest submatrix with the left upper corner at i,j, fill this matrix starting from the bottom right corner, by rows bottom to top. You'll find four cases:

    case 1: none of the right or bottom neighbour elements in the original matrix are equal to the current one, i.e: M[i,j] != M[i+1,j] and M[i,j] != M[i,j+1] being M the original matrix, in this case, the value of A[i,j] is 1x1

    case 2: the neighbour element to the right is equal to the current one but the bottom one is different, the value of A[i,j].width is A[i+1,j].width+1 and A[i,j].height=1

    case 3: the neighbour element to the bottom is equal but the right one is different, A[i,j].width=1, A[i,j].height=A[i,j+1].height+1

    case 4: both neighbours are equal: A[i,j].width = min(A[i+1,j].width+1,A[i,j+1].width) and A[i,j].height = min(A[i,j+1]+1,A[i+1,j])

    the size of the largest matrix that has the upper left corner at i,j is A[i,j].width*A[i,j].height so you can update the max value found while calculating the A[i,j]

    the bottom row and the rightmost column elements are treated as if their neighbours to the bottom and to the right respectively are different

    in your example, the resulting matrix A would be:

    {2:2 1:2 1:1}
    {2:1 1:1 1:1}
    {1:1 1:1 1:1}
    

    being w:h width:height

提交回复
热议问题