二维列表扫雷任务?[Python]

jgwigjjp  于 2023-01-03  发布在  Python
关注(0)|答案(1)|浏览(98)

我试图创建一个扫雷器,我创建了一个#-的网格函数,其中每个#是一个地雷,-是一个无地雷点,然后返回一个网格,其中每个破折号被替换为一个数字,表示周围的地雷。
输入示例:

[["-", "-", "-", "#", "#"],
["-", "#", "-", "-", "-"]] etc. etc.

输出示例:

[["1","1","2","#","#"],
["1","#","2","2","2"]]

(我本来希望网格实际上是一个5X5)
我完全不知道如何做到这一点,所以任何帮助都将不胜感激。

vof42yt1

vof42yt11#

你可以使用嵌套的for循环来遍历二维列表中的每个元素,然后如果这个元素不是一个mine,那么计算有多少个邻居是mine,就像这样:

def genPuzzle(grid):
    puzzle = []
    for i in range(len(grid)):
        puzzle.append(grid[i][:])
        for j in range(len(grid[i])):
            if grid[i][j] == '#':
                continue
            neighbors = 0
            for d in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1),
                      (1, -1), (-1, 1)]:
                di, dj = i + d[0], j + d[1]
                try:
                    if di >= 0 and dj >= 0 and grid[di][dj] == '#':
                        neighbors += 1
                except IndexError:
                    pass
            puzzle[i][j] = neighbors
    return puzzle

grid = [["-", "-", "-", "#", "#"],
        ["-", "#", "-", "-", "-"]]
print(genPuzzle(grid))

相关问题