[LeetCode] 803. Bricks Falling When Hit 打击砖块掉落
We have a grid of 1s and 0s; the 1s in a cell represent bricks. A brick will not drop if and only if it is directly connected to the top of the grid, or at least one of its (4-way) adjacent bricks will not drop.
We will do some erasures sequentially. Each time we want to do the erasure at the location (i, j), the brick (if it exists) on that location will disappear, and then some other bricks may drop because of that erasure.
Return an array representing the number of bricks that will drop after each erasure in sequence.
Example 1:
Input:
grid = [[1,0,0,0],[1,1,1,0]]
hits = [[1,0]]
Output: [2]
Explanation:
If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. So we should return 2.
Example 2:
Input:
grid = [[1,0,0,0],[1,1,0,0]]
hits = [[1,1],[1,0]]
Output: [0,0]
Explanation:
When we erase the brick at (1, 0), the brick at (1, 1) has already disappeared due to the last move.
So each erasure will cause no bricks dropping.
Note that the erased brick (1, 0) will not be counted as a dropped brick.
Note:
- The number of rows and columns in the grid will be in the range [1, 200].
- The number of erasures will not exceed the area of the grid.
- It is guaranteed that each erasure will be different from any other erasure, and located inside the grid.
- An erasure may refer to a location with no brick - if it does, no bricks drop.
解法:Union Find
Java:
public int[] hitBricks(int[][] grid, int[][] hits) {
int r[] = new int[hits.length], d[] = {-1, 0, 1, 0, -1};
for (int[] h : hits)
grid[h[0]][h[1]] -= 1;
for (int i = 0; i < grid[0].length; i++)
dfs(0, i, grid);
for (int k = hits.length - 1; k >= 0; k--) {
int h[] = hits[k], i = h[0], j = h[1];
grid[i][j] += 1;
if (grid[i][j] == 1 && isConnected(i, j, grid, d))
r[k] = dfs(i, j, grid) - 1;
}
return r;
} int dfs(int i, int j, int[][] g) {
if (i < 0 || i >= g.length || j < 0 || j >= g[0].length || g[i][j] != 1) return 0;
g[i][j] = 2;
return 1 + dfs(i + 1, j, g) + dfs(i - 1, j, g) + dfs(i, j + 1, g) + dfs(i, j - 1, g);
} boolean isConnected(int i, int j, int[][] g, int[] d) {
if (i == 0) return true;
for (int k = 1; k < d.length; k++) {
int r = i + d[k - 1], c = j + d[k];
if (0 <= r && r < g.length && 0 <= c && c < g[0].length && g[r][c] == 2)
return true;
}
return false;
}
Python:
class Solution:
def hitBricks(self, grid, hits):
"""
:type grid: List[List[int]]
:type hits: List[List[int]]
:rtype: List[int]
""" m, n = len(grid), len(grid[0]) # Connect unconnected bricks and
def dfs(i, j):
if not (0<=i<m and 0<=j<n) or grid[i][j]!=1:
return 0
ret = 1
grid[i][j] = 2
ret += sum(dfs(x, y) for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)])
return ret # Check whether (i, j) is connected to Not Falling Bricks
def is_connected(i, j):
return i==0 or any([0<=x<m and 0<=y<n and grid[x][y]==2 for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]]) # Mark whether there is a brick at the each hit
for i, j in hits:
grid[i][j] -= 1 # Get grid after all hits
for i in range(n):
dfs(0, i) # Reversely add the block of each hits and get count of newly add bricks
ret = [0]*len(hits)
for k in reversed(range(len(hits))):
i, j = hits[k]
grid[i][j] += 1
if grid[i][j]==1 and is_connected(i, j):
ret[k] = dfs(i, j)-1 return ret
Python:
class UnionFind(object):
def __init__(self, n):
self.set = range(n+1)
self.size = [1]*(n+1)
self.size[-1] = 0 def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x]) # path compression.
return self.set[x] def union_set(self, x, y):
x_root, y_root = map(self.find_set, (x, y))
if x_root == y_root:
return False
self.set[min(x_root, y_root)] = max(x_root, y_root)
self.size[max(x_root, y_root)] += self.size[min(x_root, y_root)]
return True def top(self):
return self.size[self.find_set(len(self.size)-1)] class Solution(object):
def hitBricks(self, grid, hits):
"""
:type grid: List[List[int]]
:type hits: List[List[int]]
:rtype: List[int]
"""
def index(C, r, c):
return r*C+c directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
R, C = len(grid), len(grid[0]) hit_grid = [row[:] for row in grid]
for i, j in hits:
hit_grid[i][j] = 0 union_find = UnionFind(R*C)
for r, row in enumerate(hit_grid):
for c, val in enumerate(row):
if not val:
continue
if r == 0:
union_find.union_set(index(C, r, c), R*C)
if r and hit_grid[r-1][c]:
union_find.union_set(index(C, r, c), index(C, r-1, c))
if c and hit_grid[r][c-1]:
union_find.union_set(index(C, r, c), index(C, r, c-1)) result = []
for r, c in reversed(hits):
prev_roof = union_find.top()
if grid[r][c] == 0:
result.append(0)
continue
for d in directions:
nr, nc = (r+d[0], c+d[1])
if 0 <= nr < R and 0 <= nc < C and hit_grid[nr][nc]:
union_find.union_set(index(C, r, c), index(C, nr, nc))
if r == 0:
union_find.union_set(index(C, r, c), R*C)
hit_grid[r][c] = 1
result.append(max(0, union_find.top()-prev_roof-1))
return result[::-1]
C++:
// Time: O(r * c)
// Space: O(r * c) class Solution {
public:
vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) {
static const vector<pair<int, int>> directions{{-1, 0}, { 1, 0},
{ 0, 1}, { 0, -1}};
const int R = grid.size();
const int C = grid[0].size();
const auto index = [&C](int r, int c) { return r * C + c; }; vector<vector<int>> hit_grid(grid);
for (const auto& hit : hits) {
hit_grid[hit[0]][hit[1]] = 0;
} UnionFind union_find(R * C);
for (int r = 0; r < hit_grid.size(); ++r) {
for (int c = 0; c < hit_grid[r].size(); ++c) {
if (!hit_grid[r][c]) {
continue;
}
if (r == 0) {
union_find.union_set(index(r, c), R * C);
}
if (r && hit_grid[r - 1][c]) {
union_find.union_set(index(r, c), index(r - 1, c));
}
if (c && hit_grid[r][c - 1]) {
union_find.union_set(index(r, c), index(r, c - 1));
}
}
} vector<int> result;
for (int i = hits.size() - 1; i >= 0; --i) {
const auto r = hits[i][0], c = hits[i][1];
const auto prev_roof = union_find.top();
if (grid[r][c] == 0) {
result.emplace_back(0);
continue;
}
for (const auto& d : directions) {
const auto nr = r + d.first, nc = c + d.second;
if (0 <= nr && nr < R &&
0 <= nc && nc < C &&
hit_grid[nr][nc]) {
union_find.union_set(index(r, c), index(nr, nc));
}
}
if (r == 0) {
union_find.union_set(index(r, c), R * C);
}
hit_grid[r][c] = 1;
result.emplace_back(max(0, union_find.top() - prev_roof - 1));
}
reverse(result.begin(), result.end());
return result;
} private:
class UnionFind {
public:
UnionFind(const int n) : set_(n + 1), size_(n + 1, 1) {
iota(set_.begin(), set_.end(), 0);
size_.back() = 0;
} int find_set(const int x) {
if (set_[x] != x) {
set_[x] = find_set(set_[x]); // Path compression.
}
return set_[x];
} bool union_set(const int x, const int y) {
int x_root = find_set(x), y_root = find_set(y);
if (x_root == y_root) {
return false;
}
set_[min(x_root, y_root)] = max(x_root, y_root);
size_[max(x_root, y_root)] += size_[min(x_root, y_root)];
return true;
} int top() {
return size_[find_set(size_.size() - 1)];
} private:
vector<int> set_;
vector<int> size_;
};
};
All LeetCode Questions List 题目汇总
[LeetCode] 803. Bricks Falling When Hit 打击砖块掉落的更多相关文章
- [Swift]LeetCode803. 打砖块 | Bricks Falling When Hit
We have a grid of 1s and 0s; the 1s in a cell represent bricks. A brick will not drop if and only i ...
- [LeetCode] Bricks Falling When Hit 碰撞时砖头掉落
We have a grid of 1s and 0s; the 1s in a cell represent bricks. A brick will not drop if and only i ...
- Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划)
Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划) 题目描述 已知一个正方形二维数组A,我们想找到一条最小下降路径的和 所谓下降路径是指,从一行到 ...
- Java实现 LeetCode 803 打砖块 (DFS)
803. 打砖块 我们有一组包含1和0的网格:其中1表示砖块. 当且仅当一块砖直接连接到网格的顶部,或者它至少有一块相邻(4 个方向之一)砖块不会掉落时,它才不会落下. 我们会依次消除一些砖块.每当我 ...
- LeetCode 931. Minimum Falling Path Sum
原题链接在这里:https://leetcode.com/problems/minimum-falling-path-sum/ 题目: Given a square array of integers ...
- [LeetCode] 931. Minimum Falling Path Sum 下降路径最小和
Given a square array of integers A, we want the minimum sum of a falling path through A. A falling p ...
- 【leetcode】699. Falling Squares
题目如下: On an infinite number line (x-axis), we drop given squares in the order they are given. The i- ...
- leetcode 学习心得 (4)
645. Set Mismatch The set S originally contains numbers from 1 to n. But unfortunately, due to the d ...
- All LeetCode Questions List 题目汇总
All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...
随机推荐
- Go - IDE的选择与GoLand的安装
目录 常用编辑器的选择 IDE的选择 GoLand的下载与安装 下载 安装 常用编辑器的选择 编写go程序,可以选择的编辑软件有很多,其中包括: notepad++ sublime visual st ...
- java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone.
java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized or represents more tha ...
- 1220 Vue与Django前后端的结合
目录 vue的安装 Vue前端的设置 页面的分布 后台数据的替换 css样式 Django的配置 国际化配置 axios插件安装 CORS跨域问题(同源策略) 处理跨域问题: cors插件 axios ...
- NOIP爆炸记
NOIP爆炸游记 Day 0 Day 1 T1 T2 T3 Day 2 T1 T2 T3 最后 Day 0 复习模板 + 做真题 + 方 Day 1 早上吃了一片面包,就进了考场- T1 Exm??这 ...
- 11-ESP8266 SDK开发基础入门篇--软硬件定时器
https://www.cnblogs.com/yangfengwu/p/11094009.html 定时器有两种,软件定时器和硬件定时器 软件定时器就是靠里面的任务延时实现的,,这样的定时器其实延时 ...
- C++之Lambda研究
目录 目录 1 1. 前言 1 2. 示例1 1 3. 示例2 2 4. 示例3 3 5. 示例4 3 6. 示例5 6 7. 匿名类规则 6 8. 参考资料 7 1. 前言 本文代码测试环境为“GC ...
- 73: luogu 2014 树形dp
$des$ 在大学里每个学生,为了达到一定的学分,必须从很多课程里选择一些课程来学习,在课程里有些课程必须在某些课程之前学习,如高等数学总是在其它课程之前学习.现在有N门功课,每门课有个学分,每门课有 ...
- 特征缩放(Feature Scaling)
特征缩放的几种方法: (1)最大最小值归一化(min-max normalization):将数值范围缩放到 [0, 1] 区间里 (2)均值归一化(mean normalization):将数值范围 ...
- Good Morning
题目链接:Good Morning 题目大意:按键盘上的数字,只能在此位置的基础上往右往下按,要求输出与所给值差的绝对值最小的数 AC代码如下: #include <iostream> # ...
- 不能对以下表使用 TRUNCATE TABLE
1.由 FOREIGN KEY 约束引用的表.(您可以截断具有引用自身的外键的表.) 2.参与索引视图的表. 3.通过使用事务复制或合并复制发布的表. 4.对于具有以上一个或多个特征的表,请使用 DE ...