Largest rectangular sub matrix with the same number

后端 未结 4 1051
醉梦人生
醉梦人生 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 18:22

    Modification to the above answer:

    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: Three rectangles are considered: 1. A[i,j].width=A[i,j+1].width+1; A[i,j].height=1;

    1. A[i,j].height=A[i+1,j].height+1; a[i,j].width=1;

    2. 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 one with the max area in the above three cases will be considered to represent the rectangle at this position.

    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.

提交回复
热议问题