LeetCode //C - 221. Maximal Square

221. Maximal Square

Given an m x n binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.
 

Example 1:

在这里插入图片描述

Input: matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]]
Output: 4

Example 2:

在这里插入图片描述

Input: matrix = [[“0”,“1”],[“1”,“0”]]
Output: 1

Constraints:
  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 300
  • matrix[i][j] is ‘0’ or ‘1’.

From: LeetCode
Link: 221. Maximal Square


Solution:

Ideas:
  1. Create a two-dimensional array dp of the same size as the input matrix to store the size of the largest square ending at that position.

  2. Initialize the first row and first column of dp to be the same as the input matrix since the largest square for these positions can only be 1 if the corresponding input is 1, or 0 otherwise.

  3. Iterate through the matrix starting from the second row and second column, and for each 1 encountered, set dp[i][j] to be the minimum of dp[i-1][j], dp[i][j-1], and dp[i-1][j-1] plus 1. This represents the largest square that can be formed ending at that position.

  4. Keep track of the maximum size encountered in the dp array as this represents the side length of the largest square.

  5. The area of the largest square is the maximum size squared.

Code:
int maximalSquare(char** matrix, int matrixSize, int* matrixColSize) {
    int maxSide = 0; // To keep track of the maximum side length of the square
    // dp array
    int dp[matrixSize][*matrixColSize];
    memset(dp, 0, sizeof(dp)); // Initialize dp array with 0

    // Initialize first row and first column of dp array
    for (int i = 0; i < matrixSize; i++) {
        for (int j = 0; j < *matrixColSize; j++) {
            if (i == 0 || j == 0) {
                dp[i][j] = matrix[i][j] - '0'; // Convert char to int
            }
            maxSide = max(maxSide, dp[i][j]); // Update maxSide
        }
    }

    // Compute the rest of the dp array
    for (int i = 1; i < matrixSize; i++) {
        for (int j = 1; j < *matrixColSize; j++) {
            if (matrix[i][j] == '1') {
                dp[i][j] = min(min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
                maxSide = max(maxSide, dp[i][j]); // Update maxSide
            }
        }
    }

    return maxSide * maxSide; // Return the area
}

// Helper function to find the minimum of two numbers
int min(int a, int b) {
    return (a < b) ? a : b;
}

// Helper function to find the maximum of two numbers
int max(int a, int b) {
    return (a > b) ? a : b;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值