Skip to content

Commit b7c6681

Browse files
authored
Update 803-bricks-falling-when-hit.js
1 parent 9b9dc41 commit b7c6681

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed

803-bricks-falling-when-hit.js

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,94 @@ const getConnectedCount = (grid, i, j) => {
6666
getConnectedCount(grid, i, j - 1)
6767
return count
6868
}
69+
70+
// another
71+
72+
/**
73+
* @param {number[][]} grid
74+
* @param {number[][]} hits
75+
* @return {number[]}
76+
*/
77+
const hitBricks = function (grid, hits) {
78+
const SPACE = 0
79+
const BRICK = 1
80+
const WILL_HIT = 2
81+
const DIRECTIONS = [
82+
[0, 1],
83+
[1, 0],
84+
[0, -1],
85+
[-1, 0],
86+
]
87+
const rows = grid.length
88+
const cols = grid[0].length
89+
const ds = new DisjointSet(rows * cols + 1)
90+
91+
for (const [hitR, hitC] of hits) {
92+
if (grid[hitR][hitC] === BRICK) {
93+
grid[hitR][hitC] = WILL_HIT
94+
}
95+
}
96+
97+
function hash(r, c) {
98+
return r * cols + c + 1
99+
}
100+
101+
function unionAround(r, c) {
102+
const hashed = hash(r, c)
103+
for (const [rDiff, cDiff] of DIRECTIONS) {
104+
const rNext = r + rDiff
105+
const cNext = c + cDiff
106+
if (grid[rNext] !== undefined && grid[rNext][cNext] === BRICK) {
107+
ds.union(hashed, hash(rNext, cNext))
108+
}
109+
}
110+
if (r === 0) ds.union(0, hashed)
111+
}
112+
for (let i = 0; i < grid.length; i++) {
113+
for (let j = 0; j < grid[i].length; j++) {
114+
if (grid[i][j] === BRICK) unionAround(i, j)
115+
}
116+
}
117+
let numBricksLeft = ds.size[ds.find(0)]
118+
const numBricksDropped = new Array(hits.length)
119+
// backwards
120+
for (let i = hits.length - 1; i >= 0; i--) {
121+
const [hitR, hitC] = hits[i]
122+
if (grid[hitR][hitC] === WILL_HIT) {
123+
grid[hitR][hitC] = BRICK
124+
unionAround(hitR, hitC)
125+
const newNumBricksLeft = ds.size[ds.find(0)]
126+
numBricksDropped[i] = Math.max(newNumBricksLeft - numBricksLeft - 1, 0)
127+
numBricksLeft = newNumBricksLeft
128+
} else {
129+
numBricksDropped[i] = 0
130+
}
131+
}
132+
return numBricksDropped
133+
}
134+
135+
class DisjointSet {
136+
constructor(n) {
137+
this.size = new Array(n).fill(1)
138+
this.parent = new Array(n)
139+
for (let i = 0; i < n; i++) {
140+
this.parent[i] = i
141+
}
142+
}
143+
find(x) {
144+
if (x === this.parent[x]) return x
145+
this.parent[x] = this.find(this.parent[x])
146+
147+
return this.parent[x]
148+
}
149+
union(x, y) {
150+
const rootX = this.find(x)
151+
const rootY = this.find(y)
152+
if (rootX !== rootY) {
153+
// attach X onto Y
154+
this.parent[rootX] = rootY
155+
this.size[rootY] += this.size[rootX]
156+
}
157+
}
158+
}
159+

0 commit comments

Comments
 (0)