input4x4 grid; 4-neighbor land onlystackemptyresult3 islands
Recognize it
The task asks for connected groups in a binary grid under four-direction adjacency, so every unseen land cell identifies exactly one not-yet-counted component.
Keep true
Before the scan advances, every visited land cell has been changed to 0; each stack contains only cells from the current island, and each completed island can never be counted again.
Reuse it
For regions, blobs, and connected-component problems, scan for unseen seeds, count seeds rather than cells, and exhaustively mark each seed’s reachable component before continuing.
Read it this way: Row-major scan reaches unseen land (0,0): increment islands to 1, change it to 0, and initialize stack=[(0,0)]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Pattern: DFS from each unseen land cell.
Simple idea: Each unseen land cell starts one new island. DFS changes every connected
land cell to water, so that island is never counted again.
def num_islands(grid: list[list[str]]) -> int: islands = 0 for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] != "1": continue islands += 1 grid[row][col] = "0" stack = [(row, col)] while stack: current_row, current_col = stack.pop() for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)): new_row = current_row + row_step new_col = current_col + col_step if 0 <= new_row < len(grid) and 0 <= new_col < len(grid[0]): if grid[new_row][new_col] == "1": grid[new_row][new_col] = "0" stack.append((new_row, new_col)) return islands