开发者

Finding largest square submatrix of ones in a given square matrix of 0's and 1's?

The following was given as an interview question:

Write a function that outputs 开发者_如何学JAVAthe size of the largest square submatrix consisting solely of ones in a square matrix of ones and zeros.

Example 1:

0 1
0 0

Output: 1

Example 2:

0 0 0
0 1 1
0 1 1

Output: 2

Example 3:

1 1 1
1 1 1
1 1 1

Output 3

I was hoping for an efficient solution to this problem if at all possible.


Use Search and then Dynamic Programming.


First idea of implementation: Start search on row r=1.

Find longest sequence of ones in that row, and assign this length to x.

Try to find a square matrix of ones with side=x starting at row r. If successful, max=x. If not, decrease x and repeat this step if x>1. If nothing found, max could be 0 or 1.

Increase r, and repeat.

Then improve your algorithm (stop if remaining rows are less than current max, and so on).


Here is O(n) implementation in C# using dynamic programming. Basically you are building another matrix of biggest size (including itself) while you are reading every cell of the matrix.

    public static int LargestSquareMatrixOfOne(int[,] original_mat)
    {
        int[,] AccumulatedMatrix = new int[original_mat.GetLength(0), original_mat.GetLength(1)];
        AccumulatedMatrix[0, 0] = original_mat[0, 0];
        int biggestSize = 1;
        for (int i = 0; i < original_mat.GetLength(0); i++)
        {
            for (int j = 0; j < original_mat.GetLength(1); j++)
            {
                if (i > 0 && j > 0)
                {
                    if (original_mat[i, j] == 1)
                    {
                        AccumulatedMatrix[i, j] = Math.Min(AccumulatedMatrix[i - 1, j - 1], (Math.Min(AccumulatedMatrix[i - 1, j], AccumulatedMatrix[i, j - 1]))) + 1;
                        if (AccumulatedMatrix[i, j] > biggestSize)
                        {
                            biggestSize = AccumulatedMatrix[i, j];
                        }
                    }
                    else
                    {
                        AccumulatedMatrix[i, j] = 0;
                    }
                }
                else if ( (i > 0 && j == 0) || (j > 0 && i == 0))
                {
                    if (original_mat[i, j] == 1) { AccumulatedMatrix[i, j] = 1; }
                    else { AccumulatedMatrix[i, j] = 0; }
                }
            }
        }
        return biggestSize;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜