需求说明
输入:行数m 、列数n 、地雷数k 输出:随机扫雷地图
第一步,生成地图和随机地雷 第二步,没有地雷的格子填充数字,该数字表示周边地雷总数
思路
代码实现
下面2种实现,分别是不用numpy和用numpy,思路是一样的
from random import shuffle
m, n, k = 5, 10, 15
landmine = 9
ls = [landmine for _ in range(k)] + [0 for _ in range(m * n - k)]
shuffle(ls)
matrix = [[ls[i + j * n] for i in range(n)] for j in range(m)]
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
matrix[i][j] = sum(
1 for a in range(max(i - 1, 0), min(i + 2, m))
for b in range(max(j - 1, 0), min(j + 2, n))
if matrix[a][b] == landmine)
[print(v) for v in matrix]
import numpy as np
m, n, k = 5, 10, 15
landmine = 9
ls = [landmine for _ in range(k)] + [0 for _ in range(m * n - k)]
print(ls)
np.random.shuffle(ls)
print(ls)
matrix = np.reshape(ls, (m, n))
print(matrix)
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
matrix[i][j] = sum(
1 for a in range(max(i - 1, 0), min(i + 2, m))
for b in range(max(j - 1, 0), min(j + 2, n))
if matrix[a][b] == landmine)
print(matrix)
|