Implement it on LeetCode. You can also use BFS: text function bfs(grid, i, j): queue = [(i, j)] grid[i][j] = '0' while queue not empty: (r, c) = queue.pop() for each neighbor (nr, nc): if valid and grid[nr][nc] == '1': grid[nr][nc] = '0' queue.add((nr, nc)) BFS uses more explicit memory but avoids deep recursion.
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
$ curl repovive.com/roadmaps/maang-interview-prep/graphs/number-of-islands-implementation
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░█████████████████████████████████████████████████████████████████████████████████████████