Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
OFFSETS = [(1, 0), (-1, 0), (0, 1), (0, -1)] classSolution: defnumIslands(self, grid: List[List[str]]) -> int: ifnot grid: return0 count = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == '1': self.bfs(grid, i, j) count += 1 return count
defbfs(self, nums, i, j): queue = deque([(i, j)]) nums[i][j] = 'X' while queue: island = queue.popleft() for dx, dy in OFFSETS: x, y = island[0] + dx, island[1] + dy if x < 0or x >= len(nums) or y < 0or y >= len(nums[0]) or nums[x][y] in ['0', 'X']: continue queue.append((x, y)) nums[x][y] = 'X'
publicvoiddfs(char[][] grid, int a, int b){ if(!isValid(grid,a,b)) return; grid[a][b] = 'x'; dfs(grid, a+1, b); dfs(grid, a-1, b); dfs(grid, a, b+1); dfs(grid, a, b-1); }
publicbooleanisValid(char[][] grid, int x, int y){ if(x<0||x>=grid.length||y<0||y>=grid[0].length||grid[x][y]!='1') returnfalse; returntrue; }
classUnionFind{ int count; // # of connected components int[] parent; int[] rank;
publicUnionFind(char[][] grid){ // for problem 200 count = 0; int m = grid.length; int n = grid[0].length; parent = newint[m * n]; rank = newint[m * n]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == '1') { parent[i * n + j] = i * n + j; ++count; } rank[i * n + j] = 0; } } }