1096: Minesweeper
题目描述
Minesweeper Have you ever played Minesweeper? This cute little game comes with a certain operating system whose name we can't remember. The goal of the game is to find where all the mines are located within a M x N field. The game shows a number in a square which tells you how many mines there are adjacent to that square. Each square has at most eight adjacent squares. The 4 x 4 field on the left contains two mines, each represented by a ``'' character. If we represent the same field by the hint numbers described above, we end up with the field on the right: ... .... ... .... 100 2210 1*10 1110
解题思路
此题主要遍历每个位置下周围 '*'的个数(即地雷的个数)
解题代码如下
1.输入部分
n, m = map(int, input().split())
inputL = []
while n != 0 and m != 0:
lst = []
for i in range(n):
lst.append(input())
inputL.append(lst)
n, m = map(int, input().split())
2. 计算结果部分
combina = [ [-1,-1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1]]
def search(lst):
n, m = len(lst), len(lst[0])
result = []
for i in range(n):
t = [] #储存这一行的结果
for j in range(m):
char = lst[i][j]
tchar = []#储存该字符(char)周围的字符
for tl in list(combina):
a, b = tl
u, v = i + a, j + b
if u < n and v < m and u >= 0 and v >= 0:
#把该字符(char)周围的字符存入列表中
tchar.append(lst[u][v])
if char == '*':
t.append('*')
else:
#统计该字符(char)周围地雷的个数
t.append(str(tchar.count('*')))
result.append(t)
return result
3.打印结果部分
for i, lst in enumerate(inputL):
r = search(lst)
print(f'Field #{i+1}:')
for l in r:
print(''.join(l))
print()