@@ -348,6 +348,99 @@ class Solution:
348348
349349```
350350
351+
352+ ### Go
353+
354+ ``` go
355+ func largestIsland (grid [][]int ) int {
356+ dir := [][]int {{0 , 1 }, {1 , 0 }, {-1 , 0 }, {0 , -1 }}
357+ n := len (grid)
358+ m := len (grid[0 ])
359+ area := 0
360+ visited := make ([][]bool , n)
361+ for i := 0 ; i < n; i++ {
362+ visited[i] = make ([]bool , m)
363+ }
364+ gridNum := make (map [int ]int , 0 ) // 记录每一个岛屿的面积
365+ mark := 2 // 记录每个岛屿的编号
366+ isAllGrid := true
367+ res := 0 // 标记是否整个地图都是陆地
368+
369+ var dfs func (grid [][]int , visited [][]bool , x, y, mark int )
370+ dfs = func (grid [][]int , visited [][]bool , x, y, mark int ) {
371+ // 终止条件:访问过的节点 或者 遇到海水
372+ if visited[x][y] || grid[x][y] == 0 {
373+ return
374+ }
375+ visited[x][y] = true // 标记访问过
376+ grid[x][y] = mark // 给陆地标记新标签
377+ area++
378+ for i := 0 ; i < 4 ; i++ {
379+ nextX := x + dir[i][0 ]
380+ nextY := y + dir[i][1 ]
381+ if nextX < 0 || nextX >= len (grid) || nextY < 0 || nextY >= len (grid[0 ]) {
382+ continue
383+ }
384+ dfs (grid, visited, nextX, nextY, mark)
385+ }
386+ }
387+
388+ for i := 0 ; i < n; i++ {
389+ for j := 0 ; j < m; j++ {
390+ if grid[i][j] == 0 {
391+ isAllGrid = false
392+ }
393+ if !visited[i][j] && grid[i][j] == 1 {
394+ area = 0
395+ dfs (grid, visited, i, j, mark) // 将与其链接的陆地都标记上 true
396+ gridNum[mark] = area // 记录每一个岛屿的面积
397+ mark++ // 更新下一个岛屿编号
398+ }
399+ }
400+ }
401+ if isAllGrid {
402+ return n * m
403+ }
404+ // 根据添加陆地的位置,计算周边岛屿面积之和
405+ visitedGrid := make (map [int ]struct {}) // 标记访问过的岛屿
406+ for i := 0 ; i < n; i++ {
407+ for j := 0 ; j < m; j++ {
408+ count := 1 // 记录连接之后的岛屿数量
409+ visitedGrid = make (map [int ]struct {}) // 每次使用时,清空
410+ if grid[i][j] == 0 {
411+ for k := 0 ; k < 4 ; k++ {
412+ // 计算相邻坐标
413+ nearI := i + dir[k][0 ]
414+ nearJ := j + dir[k][1 ]
415+ if nearI < 0 || nearI >= len (grid) || nearJ < 0 || nearJ >= len (grid[0 ]) {
416+ continue
417+ }
418+ // 添加过的岛屿不要重复添加
419+ if _ , ok := visitedGrid[grid[nearI][nearJ]]; ok {
420+ continue
421+ }
422+ // 把相邻四面的岛屿数量加起来
423+ count += gridNum[grid[nearI][nearJ]]
424+ // 标记该岛屿已经添加过
425+ visitedGrid[grid[nearI][nearJ]] = struct {}{}
426+ }
427+ }
428+ res = max827 (res, count)
429+ }
430+ }
431+ return res
432+ }
433+
434+ func max827 (x , y int ) int {
435+ if x > y {
436+ return x
437+ }
438+ return y
439+ }
440+
441+ ```
442+
443+
351444### JavaScript
352445
353446``` JavaScript
@@ -411,8 +504,6 @@ return res;
411504```
412505
413506
414-
415-
416507<p align =" center " >
417508<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
418509 <img src =" ../pics/网站星球宣传海报.jpg " width =" 1000 " />
0 commit comments