1. 程式人生 > >LeetCode:221. Maximal Square(陣列中最大的正方形)

LeetCode:221. Maximal Square(陣列中最大的正方形)

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

Example:

Input: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

方法1:暴力演算法(brute force)

class Solution {
    public int maximalSquare(char[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return 0;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int max = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                int temp = getMaxSquare(matrix, i, j);
                if (max < temp) {
                     max = temp;
                }
            }
        }
        return max;
    }
    
    int getMaxSquare(char[][] matrix, int rowIndex, int colIndex) {
        int row = matrix.length;
        int col = matrix[0].length;
        if (matrix[rowIndex][colIndex] == '0') {
            return 0;
        }
        int length = 1;
        int maxSize = Math.min(row-rowIndex, col-colIndex);
        for (int size = 1; size < maxSize; size++) {
            for (int i = rowIndex; i <= rowIndex + size; i++) {
                int newCol = colIndex + size;
                if (matrix[i][newCol] == '0') {
                    return length*length;
                }
            }
            for (int j = colIndex; j <= colIndex + size; j++) {
                int newRow = rowIndex + size;
                if (matrix[newRow][j] == '0') {
                    return length*length;
                }
            }
            length ++;
        }
        return length * length;      
    }
}

時間複雜度:O(n^4)

空間複雜度:O(n)


原始碼github地址:https://github.com/zhangyu345293721/leetcode