number of islands (dfs)
1 changed files with 18 additions and 0 deletions
islands.py ADDED
View File
| @@ -0,0 +1,18 @@ | ||
| 1 | +def islands(grid): | |
| 2 | + rows, cols = len(grid), len(grid[0]) | |
| 3 | + seen = set() | |
| 4 | + | |
| 5 | + def sink(r, c): | |
| 6 | + if not (0 <= r < rows and 0 <= c < cols) or grid[r][c] != "1" or (r, c) in seen: | |
| 7 | + return | |
| 8 | + seen.add((r, c)) | |
| 9 | + for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): | |
| 10 | + sink(r + dr, c + dc) | |
| 11 | + | |
| 12 | + count = 0 | |
| 13 | + for r in range(rows): | |
| 14 | + for c in range(cols): | |
| 15 | + if grid[r][c] == "1" and (r, c) not in seen: | |
| 16 | + sink(r, c) | |
| 17 | + count += 1 | |
| 18 | + return count | |