classSolution:deflargestIsland(self,grid: List[List[int]]) ->int: n =len(grid)if n ==0:return0 m =len(grid[0])defdfs(i,j,count):ifnot0<= i < n ornot0<= j < m:return countif grid[i][j] ==0or grid[i][j] ==2:return count grid[i][j] =2 t = count +1 t =dfs(i -1, j, t) t =dfs(i +1, j, t) t =dfs(i, j -1, t) t =dfs(i, j +1, t)return t max_area =0 raw = copy.deepcopy(grid)for i inrange(n):for j inrange(m):if grid[i][j] ==0: grid[i][j] =1 cur_area =dfs(i, j, 0) max_area =max(max_area, cur_area) grid = copy.deepcopy(raw)return max_area if max_area else n * m
classSolution:deflargestIsland(self,grid: List[List[int]]) ->int: n =len(grid)if n ==0:return0 m =len(grid[0])defdfs(i,j,count,t_index):ifnot0<= i < n ornot0<= j < m:return countif grid[i][j] ==0or grid[i][j] == t_index:return count grid[i][j] = t_index t = count +1 t =dfs(i -1, j, t, t_index) t =dfs(i +1, j, t, t_index) t =dfs(i, j -1, t, t_index) t =dfs(i, j +1, t, t_index)return t index, mapping =2,dict()for i inrange(n):for j inrange(m):if grid[i][j] ==1: cur_area =dfs(i, j, 0, index) mapping[index]= cur_area index +=1 max_area =0for i inrange(n):for j inrange(m):if grid[i][j] ==0: cur_area, seen =1,set()for ti, tj in [(i -1, j), (i +1, j), (i, j -1), (i, j +1)]:if0<= ti < n and0<= tj < m and grid[ti][tj] !=0and grid[ti][tj] notin seen: cur_area += mapping[grid[ti][tj]] seen.add(grid[ti][tj]) max_area =max(max_area, cur_area)return max_area if max_area else n * m