博客
关于我
dfs算法-例题油田
阅读量:168 次
发布时间:2019-02-28

本文共 1812 字,大约阅读时间需要 6 分钟。

为了解决这个问题,我们需要计算一个网格中包含多少个不同的油藏。油藏是指相邻的油口袋,包括水平、垂直和对角线相邻的点。每个油藏的口袋数不超过100。

方法思路

  • 读取输入:首先读取输入数据,处理每个网格,直到遇到m=0,表示输入结束。
  • 初始化数据结构:使用一个二维数组来记录哪些点已经被访问过。
  • 广度优先搜索(BFS):对于每个未被访问的@点,进行BFS,将所有相连的@点标记为已访问,并计数油藏数量。
  • 输出结果:对于每个网格,输出油藏的数量。
  • 解决代码

    import sysfrom collections import dequedef main():    while True:        line = input().strip()        if not line:            continue        m, n = map(int, line.split())        if m == 0:            break        grid = []        for _ in range(m):            row = input().strip()            row = row[:n]  # 确保只取n个字符            grid.append(row)        visited = [[False for _ in range(n)] for _ in range(m)]        count = 0        for i in range(m):            for j in range(n):                if grid[i][j] == '@' and not visited[i][j]:                    queue = deque()                    queue.append((i, j))                    visited[i][j] = True                    while queue:                        x, y = queue.popleft()                        for dx in (-1, 0, 1):                            for dy in (-1, 0, 1):                                if dx == 0 and dy == 0:                                    continue                                nx = x + dx                                ny = y + dy                                if 0 <= nx < m and 0 <= ny < n:                                    if grid[nx][ny] == '@' and not visited[nx][ny]:                                        visited[nx][ny] = True                                        queue.append((nx, ny))                    count += 1        print(count)if __name__ == "__main__":    main()

    代码解释

  • 读取输入:使用循环读取每个网格的尺寸m和n,直到遇到m=0。
  • 读取网格数据:对于每个网格,读取m行数据,并确保每行有n个字符。
  • 初始化访问数组:创建一个二维布尔数组visited,记录哪些点已经被访问过。
  • BFS遍历:对于每个未被访问的@点,使用BFS标记所有相连的@点,并计数油藏数量。
  • 输出结果:处理完每个网格后,输出油藏数量。
  • 这个方法确保了每个油口袋都被正确地标记和计数,处理了所有可能的相邻情况,包括对角线。

    转载地址:http://nztj.baihongyu.com/

    你可能感兴趣的文章
    Python selenium自动化测试框架实战 —— 登录测试案例
    查看>>
    Python Selenium设计模式 —— POM
    查看>>
    Python Serial:如何使用 read 或 readline 函数一次读取多个字符
    查看>>
    Python set([]) 如何检查两个对象是否相等?一个对象需要定义哪些方法来自定义它?
    查看>>
    Python setup.py:数据文件无法复制目录:不存在或不是常规文件
    查看>>
    Python setuptools sdist:仅安装版本化文件
    查看>>
    Python Shell下使用matplotlib
    查看>>
    Python Slice How-to,我知道Python Slice,但我怎么才能使用内置的Slice对象呢?
    查看>>
    python socket分包发送数据
    查看>>
    python socket模块_Python socket模块实现TCP服务端客户端
    查看>>
    Python SOCKS5代理客户端HTTPS
    查看>>
    Python Soc网络分析:通过使用函数迭代列表来计算机会网络
    查看>>
    Python Sphinx自动摘要:成员函数的自动列表
    查看>>
    Python SQL和NoSQL数据库操作实战
    查看>>
    python stdout flush_sys.stdout.flush()方法的用法
    查看>>
    python string 运算
    查看>>
    Python str与bytes之间的转换
    查看>>
    Python subprocess ffmpeg
    查看>>
    python subprocess Permission denied Errno 13
    查看>>
    Python subprocess.call - 将变量添加到 subprocess.call
    查看>>