classSolution(object): defclosedIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ m, n = len(grid), len(grid[0]) dir = [[1,0],[-1,0],[0,1],[0,-1]] deftrv(i, j,): grid[i][j] = 1 for x, y indir: if0 <= i+x < m and0 <= j+y < n and grid[i+x][j+y] == 0: trv(i+x, j+y) # 刪去邊界島 for i inrange(m): if grid[i][0] == 0: trv(i, 0) if grid[i][n-1] == 0: trv(i, n-1) for j inrange(n): if grid[0][j] == 0: trv(0, j) if grid[m-1][j] == 0: trv(m-1, j)
# 找島 cnt = 0 for i inrange(1, m-1): for j inrange(1, n-1): if grid[i][j] == 0: cnt += 1 trv(i, j) return cnt