题解 | 挡住洪水

挡住洪水

https://www.nowcoder.com/practice/56e54f4c2e3c4a58abfe76dbc1da1d7e

from collections import deque

def count_safe_land(x, y, grid):
    visited = [[False] * y for _ in range(x)]
    directions = [(-1,0), (1,0), (0,-1), (0,1)]

    def bfs(i, j):
        queue = deque()
        queue.append((i, j))
        visited[i][j] = True
        while queue:
            ci, cj = queue.popleft()
            for di, dj in directions:
                ni, nj = ci + di, cj + dj
                if 0 <= ni < x and 0 <= nj < y and not visited[ni][nj] and grid[ni][nj] == '0':
                    visited[ni][nj] = True
                    queue.append((ni, nj))

    # 从边界开始搜索所有与边界相连的 '0'
    for i in range(x):
        for j in range(y):
            if (i == 0 or i == x-1 or j == 0 or j == y-1) and grid[i][j] == '0' and not visited[i][j]:
                bfs(i, j)

    # 统计未被访问的 '0' 数量
    safe_count = 0
    for i in range(x):
        for j in range(y):
            if grid[i][j] == '0' and not visited[i][j]:
                safe_count += 1

    return safe_count

# 示例输入读取
if __name__ == "__main__":
    x, y = map(int, input().split())
    grid = [list(input().strip()) for _ in range(x)]
    print(count_safe_land(x, y, grid))

全部评论

相关推荐

11-27 19:43
门头沟学院 C++
点赞 评论 收藏
分享
算法冲刺中:kpi面加一,面完完全没动静,感谢信都没有
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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