@@ -528,6 +528,104 @@ if __name__ == "__main__":
528528
529529### Go
530530
531+ ``` go
532+ package main
533+
534+ import " fmt"
535+
536+ func main () {
537+ var m , n int
538+ fmt.Scan (&m, &n)
539+
540+ grid := make ([][]int , m)
541+ for i := range grid {
542+ grid[i] = make ([]int , n)
543+ for j := range grid[i] {
544+ fmt.Scan (&grid[i][j])
545+ }
546+ }
547+
548+ sum := buildMaxIsland (grid)
549+ fmt.Println (sum)
550+ }
551+
552+
553+ func buildMaxIsland (grid [][]int ) int {
554+ result := 0
555+ if grid == nil || len (grid) == 0 {
556+ return result
557+ }
558+ hashMap := make (map [int ]int )
559+ islandArea := 0
560+ gridMark := 2
561+ for i := 0 ; i < len (grid); i++ {
562+ for j := 0 ; j < len (grid[0 ]); j++ {
563+ if grid[i][j] == 1 {
564+ islandArea = 0
565+ visitGrid4 (grid, i, j, &islandArea, gridMark)
566+ hashMap[gridMark] = islandArea
567+ if islandArea > result {
568+ result = islandArea
569+ }
570+ gridMark++
571+ }
572+ }
573+ }
574+
575+ for i := 0 ; i < len (grid); i++ {
576+ for j := 0 ; j < len (grid[0 ]); j++ {
577+ if grid[i][j] == 0 {
578+ sum := findNearByIsland (grid, i, j, hashMap)
579+ if sum > result {
580+ result = sum
581+ }
582+ }
583+ }
584+ }
585+
586+ return result
587+ }
588+
589+ func visitGrid4 (grid [][]int , x int , y int , preValue *int , gridMark int ) {
590+ if x < 0 || y < 0 || x >= len (grid) || y >= len (grid[0 ]) {
591+ return
592+ }
593+ // 可以省略掉visited的原因是因为grid的每个位置如果被遍历过就会被标记为gridMark,能识别出来是不是被遍历过
594+ if grid[x][y] != 1 {
595+ return
596+ }
597+ // visited[x][y] = true
598+ grid[x][y] = gridMark
599+ *preValue++
600+ visitGrid4 (grid, x+1 , y, preValue, gridMark)
601+ visitGrid4 (grid, x-1 , y, preValue, gridMark)
602+ visitGrid4 (grid, x, y+1 , preValue, gridMark)
603+ visitGrid4 (grid, x, y-1 , preValue, gridMark)
604+ }
605+
606+ func findNearByIsland (grid [][]int , x , y int , hashMap map [int ]int ) int {
607+ markSet := make (map [int ]bool )
608+ sum := 1
609+ coordinate := [][]int {{x + 1 , y}, {x - 1 , y}, {x, y + 1 }, {x, y - 1 }}
610+ for _ , arr := range coordinate {
611+ if arr[0 ] < 0 || arr[1 ] < 0 || arr[0 ] >= len (grid) || arr[1 ] >= len (grid[0 ]) {
612+ continue
613+ }
614+ if grid[arr[0 ]][arr[1 ]] == 0 {
615+ continue
616+ }
617+ gridMark := grid[arr[0 ]][arr[1 ]]
618+ if !markSet[gridMark] {
619+ markSet[gridMark] = true
620+ sum += hashMap[gridMark]
621+ }
622+ }
623+ return sum
624+ }
625+ ```
626+
627+
628+
531629### Rust
532630
533631### JavaScript
0 commit comments