题解 | 数水坑

数水坑

https://www.nowcoder.com/practice/664ca4289fcf457ba3109fdf4a7a1a05

import sys
from collections import deque

data = sys.stdin.read().strip().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
grid = []
for i in range(n):
    grid.append(list(next(it)))


def bfs(x, y):
    offset = ((1, 0), (-1, 0), (0, 1), (0, -1), (-1, -1), (1, -1), (-1, 1), (1, 1))
    stack = deque()
    stack.append((x, y))
    grid[x][y] = "."
    while stack:
        x, y = stack.popleft()
        for dx, dy in offset:
            new_x = x + dx
            new_y = y + dy
            if 0 <= new_x < n and 0 <= new_y < m and grid[new_x][new_y] == "W":
                stack.append((new_x, new_y))
                grid[new_x][new_y] = "."


ans = 0
for i in range(n):
    for j in range(m):
        if grid[i][j] == "W":
            bfs(i, j)
            ans += 1
print(ans)

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务