Skip to content

Commit 574bc89

Browse files
authored
Update 803-bricks-falling-when-hit.js
1 parent 1dd9b3d commit 574bc89

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

803-bricks-falling-when-hit.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,3 +157,42 @@ class DisjointSet {
157157
}
158158
}
159159

160+
// another
161+
162+
/**
163+
* @param {number[][]} grid
164+
* @param {number[][]} hits
165+
* @return {number[]}
166+
*/
167+
const hitBricks = function(grid, hits) {
168+
const res = Array(hits.length).fill(0), dirs = [-1, 0, 1, 0, -1]
169+
for(let [r, c] of hits) {
170+
grid[r][c] -= 1
171+
}
172+
for(let i = 0; i < grid[0].length; i++) {
173+
dfs(0, i, grid)
174+
}
175+
for(let i = hits.length - 1; i >= 0; i--) {
176+
const [r, c] = hits[i]
177+
grid[r][c] += 1
178+
if(grid[r][c] === 1 && isConnected(r, c, grid, dirs)) {
179+
res[i] = dfs(r, c, grid) - 1
180+
}
181+
}
182+
return res
183+
}
184+
function dfs(i, j, grid) {
185+
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] !== 1) return 0
186+
grid[i][j] = 2
187+
return 1 + dfs(i + 1, j, grid) + dfs(i - 1, j, grid) + dfs(i, j + 1, grid) + dfs(i, j - 1, grid)
188+
}
189+
function isConnected(i, j, grid, dirs) {
190+
if(i === 0) return true
191+
for(let k = 1; k < dirs.length; k++) {
192+
const r = i + dirs[k - 1], c = j + dirs[k]
193+
if(r >= 0 && r < grid.length && c >= 0 && c < grid[0].length && grid[r][c] === 2) {
194+
return true
195+
}
196+
}
197+
return false
198+
}

0 commit comments

Comments
 (0)