- Leetcode 3394. Check if Grid can be Cut into Sections
- 1. 解题思路
- 2. 代码实现
- 题目链接:3394. Check if Grid can be Cut into Sections
1. 解题思路
这一题的话我们只需要分别在横向和竖向上考察一下是否可以切割即可。
以横向为例,我们只需要取出所有矩形的左右边界,然后将其按照左边界有序排列,然后找出来是否存在至少两条边界使得左侧所有的矩阵的右边界均小于右侧矩阵的左边界即可。
2. 代码实现
给出python代码实现如下:
class Solution:def checkValidCuts(self, n: int, rectangles: List[List[int]]) -> bool:horizon = sorted([(x[0], x[2]) for x in rectangles])vertical = sorted([(x[1], x[3]) for x in rectangles])def is_possible(boundaries):cnt = 0rb = boundaries[0][1]for l, r in boundaries[1:]:if l >= rb:cnt += 1rb = max(rb, r)if cnt >= 2:breakreturn cnt >= 2return is_possible(horizon) or is_possible(vertical)
提交代码评测得到:耗时343ms,占用内存83.6MB。