Skip to content

Commit fc5a4bc

Browse files
authored
Create 2658-maximum-number-of-fish-in-a-grid.js
1 parent 2277886 commit fc5a4bc

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
const deepCopy2DArray = (g) => {
2+
let d = []
3+
for (const a of g) d.push([...a])
4+
return d
5+
}
6+
7+
const dx = [1, -1, 0, 0],
8+
dy = [0, 0, 1, -1]
9+
const getAllAreasCoordinates = (g) => {
10+
const forbid = 0,
11+
floodFillMakeConnected = '*' // forbid is land cell
12+
let n = g.length,
13+
m = g[0].length,
14+
res = []
15+
for (let i = 0; i < n; i++) {
16+
for (let j = 0; j < m; j++) {
17+
if (g[i][j] != forbid) {
18+
let q = [[i, j]],
19+
area = []
20+
while (q.length) {
21+
let [x, y] = q.shift()
22+
for (let k = 0; k < 4; k++) {
23+
let nx = x + dx[k],
24+
ny = y + dy[k]
25+
if (
26+
nx < 0 ||
27+
nx >= n ||
28+
ny < 0 ||
29+
ny >= m ||
30+
g[nx][ny] == forbid ||
31+
g[nx][ny] == floodFillMakeConnected
32+
)
33+
continue
34+
g[nx][ny] = floodFillMakeConnected
35+
area.push([nx, ny])
36+
q.push([nx, ny])
37+
}
38+
}
39+
if (area.length == 0 && g[i][j] != floodFillMakeConnected)
40+
area.push([i, j])
41+
res.push(area)
42+
}
43+
}
44+
}
45+
return res
46+
}
47+
48+
/**
49+
* @param {number[][]} grid
50+
* @return {number}
51+
*/
52+
const findMaxFish = (g) => {
53+
let areas = getAllAreasCoordinates(deepCopy2DArray(g)),
54+
res = 0
55+
for (const area of areas) {
56+
let sum = 0
57+
for (const [x, y] of area) sum += g[x][y]
58+
res = Math.max(res, sum)
59+
}
60+
return res
61+
}
62+

0 commit comments

Comments
 (0)