当前位置: 首页 > 工具软件 > J2Minesweeper > 使用案例 >

Python实现Minesweeper(扫雷问题)

戚明朗
2023-12-01

题目描述:
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 110 1110
简单翻译一下,内容就是我们以星号和点的形式输入进去扫雷的内容,星号表示有雷,然后我们通过代码实现符号向数字的转变,没有雷的点需要标明周围的点中雷的数量。
还是看样例比较清楚:

样例输入
4 4
*...
....
.*..
....


3 5
**...
.....
.*...
0 0
样例输出
Field #1:
*100
2210
1*10
1110

Field #2:
**100
33200
1*100

解决的代码:

num=1
while True:
	arr=[]
	final=[]
	m,n=map(int,input().split())
	#结束条件
	if m==0 and n==0:
		break
	for i in range(0,m):
	#列表形式方便单个拎出来进行判断和调整
		arr.append(list(input()))
	final=arr
	for i in range(0,m):
		for j in range(n):
			if arr[i][j]=='.':
				final[i][j]=0
	print(f"Field #{num}:")
	for i in range(0,m):
		for j in range(0,n):
			if arr[i][j]!='*':
			#判断八个方位是否有雷,注意不要超出列表范围
				if i-1>=0 and j-1>=0 and arr[i-1][j-1]=='*':
					final[i][j]+=1
				if j-1>=0 and arr[i][j-1]=='*':
					final[i][j]+=1
				if i+1<=m-1 and j-1>=0 and arr[i+1][j-1]=='*':
					final[i][j]+=1
				if i-1>=0 and arr[i-1][j]=='*':
					final[i][j]+=1
				if i+1<=m-1 and arr[i+1][j]=='*':
					final[i][j]+=1	
				if i-1>=0 and j+1<=n-1 and arr[i-1][j+1]=='*':
					final[i][j]+=1
				if j+1<=n-1 and arr[i][j+1]=='*':
					final[i][j]+=1
				if i+1<=m-1 and j+1<=n-1 and arr[i+1][j+1]=='*':
					final[i][j]+=1	
	for i in final:
		for j in i:
			print(j,end='')
		print()
	print()
	num+=1

第一次做一个相对正常点的OJ题,就多说几句,前面输入字符串的时候我们使用了list,这是因为Python对于字符串的处理这里很弱,不像C语言可以数组对单点进行处理,如果不用列表的话我们是不能处理整个的字符串的。
之后的话就是判定输出了,这里用到print函数的一些参数和操作的用法,主要就是调整输出之后的换行。
这里就感觉到多学一些语言的意义了,像这种题还是用C语言或者C++比较方便,各种语言算是各有用处吧。

 类似资料: