LeetCode每日一题(2132. Stamping the Grid)

You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied).

You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements:

Cover all the empty cells.
Do not cover any of the occupied cells.
We can put as many stamps as we want.
Stamps can overlap with each other.
Stamps are not allowed to be rotated.
Stamps must stay completely inside the grid.
Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false.

Example 1:

Input: grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3
Output: true

Explanation: We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells.

Example 2:

Input: grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2
Output: false

Explanation: There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid.

Constraints:

  • m == grid.length
  • n == grid[r].length
  • 1 <= m, n <= 105
  • 1 <= m _ n <= 2 _ 105
  • grid[r][c] is either 0 or 1.
  • 1 <= stampHeight, stampWidth <= 105

先对 grid 计算一个二维 prefix sum 记为 prefix_grid, 从 row = stamp_height - 1 和 col = stamp_width - 1 开始遍历整个 grid, 看看能否以 grid[row][col]作为 stamp 的右下角来盖印章, 检查条件就是以 grid[row+1-stamp_height][col+1-stamp_width]作为左上角, grid[row][col]为右下角, 看此范围内的 prefix_grid 的加和是不是 0, 如果是 0 则说明没有障碍可以盖章, 反之则无法盖章。我们另创建一个与 grid 尺度一样的 stamps, 将每个章的右下角的 row 和 col 标记在 stamps 里, 完成之后再对 stamps 计算二维 prefix sum 记为 prefix_stamps, 此时我们就可以挨个检查 grid 中的 cell 是不是可以被盖的章覆盖了, 检查条件就是对于 grid[row][col], 如果在[row][col]到[row+stamp_height-1][col+stamp_width-1]的范围内, prefix_stamps 的值>0 则证明有章可以覆盖[row][col], 检查的时候记得排除那些障碍 cell



impl Solution {
   
    fn prefix_2d(matrix: &Vec<Vec<i32>>) -> Vec<Vec<i32>> {
   
        let mut prefix = vec!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值