博客
关于我
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 中的... 三点、箭头(->)、/ 分别的作用
    查看>>
    python读取json数据的id_python处理JSON数据
    查看>>
    Python 中的Duck Typing
    查看>>
    Python 中的for in 遍历生成字典、添加判断条件if
    查看>>
    Python 中的Lock与RLock
    查看>>
    Python 中的range(),arange()函数
    查看>>
    Python 中的内存管理机制
    查看>>
    Python 中的函数包装器:模型运行时和调试
    查看>>
    Python 中的列表理解和 lambda
    查看>>
    Python 中的多层for in嵌套循环使用
    查看>>
    Python 中的多线程(01/4)
    查看>>
    Python 中的多进程(01/2):简介
    查看>>
    Python 中的多进程(02/2):进程之间的通信)
    查看>>
    Python 中的字符串、列表、元组和字典数据类型的特点和使用场景
    查看>>
    Python 中的属性访问器是什么?如何使用 @property 装饰器?
    查看>>
    Python 中的带宽限制
    查看>>
    Python 中的机器学习简介:多项式回归
    查看>>
    python读取grib2数据_用Python加载grib2文件
    查看>>
    Python 中的注意点_s2
    查看>>
    Python读取Excel的几种工具包(附Demo)
    查看>>