You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if:
You are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks).
Return an array result, where each result[i] is the number of bricks that will fall after the ith erasure is applied.
Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.
Example 1:
Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]] Output: [2] Explanation: Starting with the grid: [[1,0,0,0], [1,1,1,0]] We erase the underlined brick at (1,0), resulting in the grid: [[1,0,0,0], [0,1,1,0]] The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is: [[1,0,0,0], [0,0,0,0]] Hence the result is [2].
Example 2:
Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]] Output: [0,0] Explanation: Starting with the grid: [[1,0,0,0], [1,1,0,0]] We erase the underlined brick at (1,1), resulting in the grid: [[1,0,0,0], [1,0,0,0]] All remaining bricks are still stable, so no bricks fall. The grid remains the same: [[1,0,0,0], [1,0,0,0]] Next, we erase the underlined brick at (1,0), resulting in the grid: [[1,0,0,0], [0,0,0,0]] Once again, all remaining bricks are still stable, so no bricks fall. Hence the result is [0,0].
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 200grid[i][j] is 0 or 1.1 <= hits.length <= 4 * 104hits[i].length == 20 <= xi <= m - 10 <= yi <= n - 1(xi, yi) are unique.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force way to solve this is to simulate removing each brick one by one. After removing each brick, we check which bricks are still connected to the top. The bricks that aren't connected to the top will fall.
Here's how the algorithm would work step-by-step:
def bricks_falling_when_hit_brute_force(grid, hits):
rows = len(grid)
cols = len(grid[0])
results = []
def is_valid(row_coordinate, col_coordinate):
return 0 <= row_coordinate < rows and 0 <= col_coordinate < cols
def is_connected(grid_copy, row_coordinate, col_coordinate, visited):
if not is_valid(row_coordinate, col_coordinate) or grid_copy[row_coordinate][col_coordinate] == 0 or (row_coordinate, col_coordinate) in visited:
return False
if row_coordinate == 0:
return True
visited.add((row_coordinate, col_coordinate))
# Check adjacent cells
neighbors = [(row_coordinate + 1, col_coordinate), (row_coordinate - 1, col_coordinate),
(row_coordinate, col_coordinate + 1), (row_coordinate, col_coordinate - 1)]
for neighbor_row, neighbor_col in neighbors:
if is_connected(grid_copy, neighbor_row, neighbor_col, visited):
return True
return False
def count_fallen_bricks(grid_copy):
fallen_count = 0
for row_coordinate in range(rows):
for col_coordinate in range(cols):
if grid_copy[row_coordinate][col_coordinate] == 1:
visited = set()
if not is_connected(grid_copy, row_coordinate, col_coordinate, visited):
fallen_count += 1
return fallen_count
for hit in hits:
row_to_remove, col_to_remove = hit
# Temporarily remove the brick
original_value = grid[row_to_remove][col_to_remove]
grid[row_to_remove][col_to_remove] = 0
grid_copy = [row[:] for row in grid] # Create a copy for simulation
fallen_bricks = count_fallen_bricks(grid_copy)
results.append(fallen_bricks)
# Restore the brick for the next iteration
grid[row_to_remove][col_to_remove] = original_value
return resultsThe key is to reverse the problem. Instead of figuring out which bricks fall when hit, we start with the end state (after all hits) and rebuild the structure, determining which bricks must be stable based on being connected to the top.
Here's how the algorithm would work step-by-step:
def falling_bricks(grid, hits):
rows = len(grid)
columns = len(grid[0])
hit_results = []
# Mark bricks to be removed for simulation
for row_index, column_index in hits:
if grid[row_index][column_index] == 1:
grid[row_index][column_index] = 2
def perform_depth_first_search(row_index, column_index, stable_bricks):
if (row_index < 0 or row_index >= rows or
column_index < 0 or column_index >= columns or
grid[row_index][column_index] != 1 or
(row_index, column_index) in stable_bricks):
return
stable_bricks.add((row_index, column_index))
perform_depth_first_search(row_index + 1, column_index, stable_bricks)
perform_depth_first_search(row_index - 1, column_index, stable_bricks)
perform_depth_first_search(row_index, column_index + 1, stable_bricks)
perform_depth_first_search(row_index, column_index - 1, stable_bricks)
# Find stable bricks connected to the top
stable_bricks_set = set()
for column_index in range(columns):
if grid[0][column_index] == 1:
perform_depth_first_search(0, column_index, stable_bricks_set)
# Process hits in reverse order to rebuild
for row_index, column_index in reversed(hits):
if grid[row_index][column_index] == 2:
grid[row_index][column_index] = 1
else:
hit_results.append(0)
continue
initial_stable_count = len(stable_bricks_set)
# Check if the brick can become stable
perform_depth_first_search(row_index, column_index, stable_bricks_set)
# Determine number of new bricks made stable.
newly_stable_count = len(stable_bricks_set) - initial_stable_count
hit_results.append(newly_stable_count)
# Restore grid state and reverse hit_results
for row_index, column_index in hits:
if grid[row_index][column_index] == 2:
grid[row_index][column_index] = 0
hit_results.reverse()
return hit_results| Case | How to Handle |
|---|---|
| Empty grid or no bricks to hit | Return empty array if grid is empty or hits array is empty. |
| Grid is a single row or single column | Ensure correct handling of connectivity checks on the boundary when grid is very narrow. |
| All bricks are hit | The number of remaining bricks will rapidly decrease, potentially to zero. |
| Hits outside the grid bounds | Ignore hits that fall outside the grid boundaries to avoid array out of bounds errors. |
| Multiple hits on the same brick | Ensure the algorithm only counts the brick removal once even if hit multiple times. |
| Large grid dimensions | Optimize memory usage and algorithm complexity to avoid timeouts or memory errors on larger grids. |
| Bricks initially not connected to the top | These bricks should fall regardless of hits elsewhere, so ensure initial setup handles them correctly. |
| Integer overflow when calculating connected components | Use appropriate data types (e.g., long) to avoid overflow issues when counting connected bricks. |