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.
第一次遍历,踢掉所有hit
第二次遍历,确定最终不掉的砖头
第三次反向遍历hits[],把hit一个个加回去。每加一个,检查是否跟不掉砖头有连接
每个点最多被跑2次,O(N), N为矩阵的大小
class Solution { public int[] hitBricks(int[][] grid, int[][] hits) { removeHits(grid, hits); int id = 2; for (int col = 0; col < grid[0].length; col++) { dfs(grid, 0, col, id); } int[] rt = new int[hits.length]; for (int i = hits.length - 1; i >= 0; i--) { int row = hits[i][0], col = hits[i][1]; if (grid[row][col] == 0) { grid[row][col] = 1; if (checkContact(grid, row, col)) { rt[i] = dfs(grid, row, col, 2) - 1; } } } return rt; } private boolean checkContact(int[][] grid, int row, int col) { if (row == 0) return true; if (row - 1 >= 0 && grid[row - 1][col] == 2) return true; if (row + 1 < grid.length && grid[row + 1][col] == 2) return true; if (col - 1 >= 0 && grid[row][col - 1] == 2) return true; if (col + 1 < grid[0].length && grid[row][col + 1] == 2) return true; return false; } private int dfs(int[][] grid, int row, int col, int id) { if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] != 1) return 0; grid[row][col] = id; return 1 + dfs(grid, row + 1, col, id) + dfs(grid, row - 1, col, id) + dfs(grid, row, col + 1, id) + dfs(grid, row, col - 1, id); } private void removeHits(int[][] grid, int[][] hits) { for (int[] hit : hits) { if (grid[hit[0]][hit[1]] == 0) grid[hit[0]][hit[1]] = -1; else grid[hit[0]][hit[1]] = 0; } } }
No comments:
Post a Comment