@@ -366,6 +366,79 @@ public class Main {
366366
367367### Python
368368
369+ ``` Python
370+ import collections
371+
372+ directions = [[- 1 , 0 ], [0 , 1 ], [0 , - 1 ], [1 , 0 ]]
373+ area = 0
374+
375+ def dfs (i , j , grid , visited , num ):
376+ global area
377+
378+ if visited[i][j]:
379+ return
380+
381+ visited[i][j] = True
382+ grid[i][j] = num # 标记岛屿号码
383+ area += 1
384+
385+ for x, y in directions:
386+ new_x = i + x
387+ new_y = j + y
388+ if (
389+ 0 <= new_x < len (grid)
390+ and 0 <= new_y < len (grid[0 ])
391+ and grid[new_x][new_y] == " 1"
392+ ):
393+ dfs(new_x, new_y, grid, visited, num)
394+
395+
396+ def main ():
397+ global area
398+
399+ N, M = map (int , input ().strip().split())
400+ grid = []
401+ for i in range (N):
402+ grid.append(input ().strip().split())
403+ visited = [[False ] * M for _ in range (N)]
404+ rec = collections.defaultdict(int )
405+
406+ cnt = 2
407+ for i in range (N):
408+ for j in range (M):
409+ if grid[i][j] == " 1" :
410+ area = 0
411+ dfs(i, j, grid, visited, cnt)
412+ rec[cnt] = area # 纪录岛屿面积
413+ cnt += 1
414+
415+ res = 0
416+ for i in range (N):
417+ for j in range (M):
418+ if grid[i][j] == " 0" :
419+ max_island = 1 # 将水变为陆地,故从1开始计数
420+ v = set ()
421+ for x, y in directions:
422+ new_x = i + x
423+ new_y = j + y
424+ if (
425+ 0 <= new_x < len (grid)
426+ and 0 <= new_y < len (grid[0 ])
427+ and grid[new_x][new_y] != " 0"
428+ and grid[new_x][new_y] not in v # 岛屿不可重复
429+ ):
430+ max_island += rec[grid[new_x][new_y]]
431+ v.add(grid[new_x][new_y])
432+ res = max (res, max_island)
433+
434+ if res == 0 :
435+ return max (rec.values()) # 无水的情况
436+ return res
437+
438+ if __name__ == " __main__" :
439+ print (main())
440+ ```
441+
369442### Go
370443
371444### Rust
0 commit comments