764. Largest Plus Sign

1. Description

You are given an integer n. You have an n x n binary grid grid with all values initially 1’s except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.
Return the order of the largest axis-aligned plus sign of 1’s contained in grid. If there is none, return 0.
An axis-aligned plus sign of 1’s of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1’s. Note that there could be 0’s or 1’s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1’s.

2. Example

Example 1:

Input: n = 5, mines = [[4,2]]
Output: 2
Explanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown.

Example 2:

Input: n = 1, mines = [[0,0]]
Output: 0
Explanation: There is no plus sign, so return 0.

3. Constraints

  • 1 <= n <= 500
  • 1 <= mines.length <= 5000
  • 0 <= $x_i$, $y_i$ < n
  • All the pairs ($x_i$, $y_i$) are unique.

4. Solutions

Dynamic Programming

Time complexity: O($n^2$)
Space complexity: O($n^2$)

class Solution {
public:
    int orderOfLargestPlusSign(int n, const vector<vector<int>> &mines) {
        vector<vector<int>> matrix(n, vector<int>(n, 1));
        for (auto mine : mines) {
            matrix[mine[0]][mine[1]] = 0;
        }

        vector<vector<array<int, 4>>> dp(n + 2, vector<array<int, 4>>(n + 2, {0}));
        // dp[i][j][0]: up
        // dp[i][j][1]: down
        // dp[i][j][2]: left
        // dp[i][j][3]: right

        // left-up to right-down
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= n; ++j) {
                dp[i][j][0] = matrix[i - 1][j - 1] == 1 ? dp[i - 1][j][0] + 1 : 0;
                dp[i][j][2] = matrix[i - 1][j - 1] == 1 ? dp[i][j - 1][2] + 1 : 0;
            }
        }

        // right-down to left-up
        int result = 0;
        for (int i = n; i >= 1; --i) {
            for (int j = n; j >= 1; --j) {
                dp[i][j][1] = matrix[i - 1][j - 1] == 1 ? dp[i + 1][j][1] + 1 : 0;
                dp[i][j][3] = matrix[i - 1][j - 1] == 1 ? dp[i][j + 1][3] + 1 : 0;

                result = max(result, min({dp[i][j][0], dp[i][j][1], dp[i][j][2], dp[i][j][3]}));
            }
        }

        return result;
    }
};
comments powered by Disqus