''' LastEditTime: 2023-06-18 13:52:12 ''' # from typing import List
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
classSolution: defmark(self, grid: List[List[int]], x, y) -> None: q = [] grid[x][y] = 1 q.append((x, y)) while q: x, y = q.pop() for dx, dy in directions: tx = dx + x ty = dy + y if0 <= tx < len(grid) and0 <= ty < len(grid[0]) and grid[tx][ty] == 0: grid[tx][ty] = 1 q.append((tx, ty))
defclosedIsland(self, grid: List[List[int]]) -> int: for i inrange(len(grid)): if grid[i][0] == 0: self.mark(grid, i, 0) if grid[i][-1] == 0: self.mark(grid, i, len(grid[0]) - 1) for j inrange(len(grid[0])): if grid[0][j] == 0: self.mark(grid, 0, j) if grid[-1][j] == 0: self.mark(grid, len(grid) - 1, j)
ans = 0 for i inrange(1, len(grid) - 1): for j inrange(1, len(grid[0]) - 1): if grid[i][j] == 0: self.mark(grid, i, j) ans += 1 return ans
/* * @LastEditTime: 2026-10-25 09:17:30 */ classSolution { private: int n, m; staticconstexprint dirs[][2] = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
boolisCenter(int i, int j){ // 是否不是四周这一圈 return i && i != n - 1 && j && j != m - 1; }
boolinGrid(int i, int j){ return i >= 0 && i < n && j >=0 && j < m; } public: intclosedIsland(vector<vector<int>>& grid){ n = grid.size(), m = grid[0].size(); int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j]) { continue; } // 新土地 grid[i][j] = 1; bool ok = isCenter(i, j); queue<pair<int, int>> q; q.push({i, j}); while (!q.empty()) { auto [x, y] = q.front(); q.pop(); for (auto[dx, dy] : dirs) { int nx = x + dx, ny = y + dy; if (!inGrid(nx, ny) || grid[nx][ny]) { continue; } grid[nx][ny] = 1; ok &= isCenter(nx, ny); q.push({nx, ny}); } } ans += ok; } } return ans; } };
defclosedIsland(self, grid: List[List[int]]) -> int: self.n = len(grid) self.m = len(grid[0]) ans = 0 for i, line inenumerate(grid): for j, v inenumerate(line): if v: continue grid[i][j] = 1 ok = self.isCenter(i, j) q = [(i, j)] while q: x, y = q.pop() for dx, dy in dirs: nx, ny = x + dx, y + dy ifnotself.inGrid(nx, ny) or grid[nx][ny]: continue grid[nx][ny] = 1 ok &= self.isCenter(nx, ny) q.append((nx, ny)) ans += ok return ans
funcclosedIsland(grid [][]int) (ans int) { n, m := len(grid), len(grid[0]) for i, line := range grid { for j, v := range line { if v == 1 { continue } ok := isCenter1254(i, j, n, m) grid[i][j] = 1 q := [][2]int{{i, j}} forlen(q) > 0 { top := q[len(q) - 1] q = q[:len(q) - 1] x, y := top[0], top[1] for _, d := range dirs1254 { nx, ny := x + d[0], y + d[1] if !inGrid1254(nx, ny, n, m) || grid[nx][ny] == 1 { continue } grid[nx][ny] = 1 ok = ok && isCenter1254(nx, ny, n, m) // go没有bool的& q = append(q, [2]int{nx, ny}) } } if ok { ans++ } } } return }