Python 递归算法采蘑菇代码示例
以下是一个简单的采蘑菇的代码示例,使用 Python 递归算法实现:
def collect_mushrooms(grid, row, col):
# 检查坐标是否越界或者当前位置不是蘑菇
if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]) or grid[row][col] != 'M':
return 0
# 将当前位置的蘑菇收集
grid[row][col] = 'X'
# 递归地从上、下、左、右四个方向采蘑菇
count = 1
count += collect_mushrooms(grid, row-1, col)
count += collect_mushrooms(grid, row+1, col)
count += collect_mushrooms(grid, row, col-1)
count += collect_mushrooms(grid, row, col+1)
return count
# 采蘑菇的主函数
def main():
# 定义一个蘑菇地图
grid = [
['M', 'M', 'M', 'M', 'M'],
['M', 'M', 'M', 'M', 'M'],
['M', 'M', 'M', 'M', 'M'],
['M', 'M', 'M', 'M', 'M'],
['M', 'M', 'M', 'M', 'M']
]
# 选择一个起始位置
start_row = 2
start_col = 2
# 采蘑菇,并输出结果
count = collect_mushrooms(grid, start_row, start_col)
print('共采集到了', count, '个蘑菇')
# 调用主函数
main()
这段代码通过递归的方式,从给定的起始位置开始,向上、下、左、右四个方向搜索蘑菇。每次搜索到一个蘑菇时,将其收集并标记为已访问。最后输出总共采集到的蘑菇数量。
原文地址: https://www.cveoy.top/t/topic/bCcg 著作权归作者所有。请勿转载和采集!