Skip to content

Commit 9b9dc41

Browse files
authored
Create 803-bricks-falling-when-hit.js
1 parent 5ce9854 commit 9b9dc41

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

803-bricks-falling-when-hit.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @param {number[][]} hits
4+
* @return {number[]}
5+
*/
6+
const hitBricks = function (grid, hits) {
7+
const n = grid[0].length
8+
const m = hits.length
9+
const res = new Array(m).fill(0)
10+
for (const [r, c] of hits) {
11+
if (grid[r][c] == 1) grid[r][c] = 0
12+
else grid[r][c] = -1
13+
}
14+
for (let j = 0; j < n; j++) {
15+
getConnectedCount(grid, 0, j)
16+
}
17+
for (let i = m - 1; i >= 0; i--) {
18+
const [r, c] = hits[i]
19+
if (grid[r][c] == -1) continue
20+
grid[r][c] = 1
21+
if (isConnectedToTop(grid, r, c)) {
22+
res[i] = getConnectedCount(grid, r, c) - 1
23+
}
24+
}
25+
return res
26+
}
27+
const isConnectedToTop = (grid, i, j) => {
28+
if (i == 0) return true
29+
const dircs = [
30+
[-1, 0],
31+
[1, 0],
32+
[0, -1],
33+
[0, 1],
34+
]
35+
for (const [dx, dy] of dircs) {
36+
const nx = i + dx
37+
const ny = j + dy
38+
if (
39+
0 <= nx &&
40+
nx < grid.length &&
41+
0 <= ny &&
42+
ny < grid[0].length &&
43+
grid[nx][ny] == 2
44+
) {
45+
return true
46+
}
47+
}
48+
return false
49+
}
50+
51+
const getConnectedCount = (grid, i, j) => {
52+
if (
53+
i < 0 ||
54+
i >= grid.length ||
55+
j < 0 ||
56+
j >= grid[0].length ||
57+
grid[i][j] != 1
58+
)
59+
return 0
60+
let count = 1
61+
grid[i][j] = 2
62+
count +=
63+
getConnectedCount(grid, i + 1, j) +
64+
getConnectedCount(grid, i - 1, j) +
65+
getConnectedCount(grid, i, j + 1) +
66+
getConnectedCount(grid, i, j - 1)
67+
return count
68+
}

0 commit comments

Comments
 (0)