Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b132f52

Browse files
Merge pull request youngyangyang04#2446 from hp1998318/master
0827:最大人工岛----添加js解法
2 parents fe137e0 + a45fd00 commit b132f52

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

‎problems/0827.最大人工岛.md‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,71 @@ class Solution:
348348

349349
```
350350

351+
### JavaScript
352+
353+
```JavaScript
354+
355+
var largestIsland = function(grid) {
356+
let res = 0;
357+
const m = grid.length;
358+
const n = grid[0].length;
359+
const tag = new Array(n).fill().map(_ => new Array(m).fill(0));
360+
const area = new Map();
361+
const dir = [[0,1],[0,-1],[1,0],[-1,0]];
362+
const dfs = (grid,tag,x,y,mark) => {
363+
let res = 1;
364+
tag[x][y] = mark;
365+
for(let i = 0; i < dir.length; i++) {
366+
let nextX = x + dir[i][0];
367+
let nextY = y + dir[i][1];
368+
if(nextX < 0 || nextX >= m || nextY < 0 || nextY >= n) {
369+
continue;
370+
}
371+
if(grid[nextX][nextY] === 1 && tag[nextX][nextY] === 0) {
372+
res += dfs(grid,tag,nextX,nextY,mark);
373+
}
374+
}
375+
return res;
376+
}
377+
let mark = 2;
378+
//将岛屿用mark标记
379+
for(let i = 0; i < m; i++) {
380+
for(let j = 0; j < n; j++) {
381+
if(grid[i][j] === 1 && tag[i][j] === 0) {
382+
area.set(mark,dfs(grid,tag,i,j,mark));
383+
res = Math.max(res,area.get(mark));
384+
mark++;
385+
}
386+
}
387+
}
388+
//将一个非岛屿格子变为岛屿
389+
for(let i = 0; i < m; i++) {
390+
for(let j = 0; j < n; j++) {
391+
if(grid[i][j] === 0) {
392+
let z = 1;
393+
const connected = new Set();
394+
for(let k = 0; k < dir.length; k++) {
395+
let nextX = i + dir[k][0];
396+
let nextY = j + dir[k][1];
397+
if(nextX < 0 || nextX >= m || nextY < 0 || nextY >= n || tag[nextX][nextY] === 0 || connected.has(tag[nextX][nextY])) {
398+
continue;
399+
}
400+
z += area.get(tag[nextX][nextY]);
401+
connected.add(tag[nextX][nextY]);
402+
}
403+
res = Math.max(res,z);
404+
}
405+
}
406+
}
407+
return res;
408+
};
409+
410+
411+
```
412+
413+
414+
415+
351416
<p align="center">
352417
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
353418
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /