LeetCode 题解(117): Maximal Square

题目:

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

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.

题解:

动态规划: when matrix[i][j] == '1', sides[i][j] = min(sides[i-1][j-1], min(sides[i-1][j], sides[i][j-1])) + 1

C++版:

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        if(matrix.size() == 0)
            return 0;
        vector<vector<int>> sides(matrix.size() + 1, vector<int>(matrix[0].size() + 1, 0));
        int maxSide = 0;
        for(int i = 1; i <= matrix.size(); i++) {
            for(int j = 1; j <= matrix[0].size(); j++) {
                if(matrix[i-1][j-1] == '1') {
                    sides[i][j] = min(sides[i-1][j-1], min(sides[i][j-1], sides[i-1][j])) + 1;
                    if(sides[i][j] > maxSide)
                        maxSide = sides[i][j];
                }
            }
        }
        return maxSide * maxSide;
    }
};

Java版:

public class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix.length == 0)
            return 0;
        int[][] sides = new int[matrix.length + 1][matrix[0].length + 1];
        int maxSide = 0;
        for(int i = 1; i <= matrix.length; i++) {
            for(int j = 1; j <= matrix[0].length; j++) {
                if(matrix[i-1][j-1] == '1') {
                    sides[i][j] = Math.min(sides[i-1][j-1], Math.min(sides[i-1][j], sides[i][j-1])) + 1;
                    if(sides[i][j] > maxSide)
                        maxSide = sides[i][j];
                }
            }
        }
        return maxSide * maxSide;
    }
}

Python版:

class Solution:
    # @param {character[][]} matrix
    # @return {integer}
    def maximalSquare(self, matrix):
        maxSide = 0
        if len(matrix) == 0:
            return 0
        side = [[0] * (len(matrix[0])+1) for i in range(len(matrix) + 1)]
        for i in range(1, len(matrix) + 1):
            for j in range(1, len(matrix[0]) + 1):
                if matrix[i-1][j-1] == '1':
                    side[i][j] = min(side[i-1][j-1], min(side[i-1][j], side[i][j-1])) + 1
                    if side[i][j] > maxSide:
                        maxSide = side[i][j]
                    
        return maxSide * maxSide

你可能感兴趣的:(Algorithm,LeetCode,面试题)