随机填充大小为10×10 True和False的数组,显示为1和0,并输出从1s跳到1s所需的国际象棋骑士数量并访问所有1(他们可以跳回到之前访问过的位置)。
# Randomly fills an array of size 10x10 True and False, displayed as 1 and 0,
# and outputs the number chess knights needed to jump from 1s to 1s
# and visit all 1s (they can jump back to locations previously visited).
#
# Written by *** and Eric Martin for COMP9021
from random import seed, randrange
import sys
dim = 10
def display_grid():
for i in range(dim):
print(' ', end = '')
print(' '.join(grid[i][j] and '1' or '0' for j in range(dim)))
print()
def check():
for i in range(dim):
for j in range(dim):
if grid[i][j]== True:
entry = (i,j)
return entry
return (-1,-1)
def explore_board():
nb_of_knights = 0
l= []
p = [(-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1)]
while check()!=(-1,-1):
nb_of_knights +=1
(r,t) = check()
grid[r][t] = False
l.append((r,t))
while len(l)>0:
(i,j) = l.pop()
for (x,y) in p:
a = x+i
b = y+j
if a< dim and b <dim and a>-1 and b >-1:
if grid[a][b] == True:
l.append((a,b))
grid[a][b] = False
return nb_of_knights
try:
for_seed, n = (int(i) for i in input('Enter two integers: ').split())
if not n:
raise ValueError
except ValueError:
print('Incorrect input, giving up.')
sys.exit()
seed(for_seed)
if n > 0:
grid = [[randrange(n) > 0 for _ in range(dim)] for _ in range(dim)]
else:
grid = [[randrange(-n) == 0 for _ in range(dim)] for _ in range(dim)]
print('Here is the grid that has been generated:')
display_grid()
nb_of_knights = explore_board()
if not nb_of_knights:
print('No chess knight has explored this board.')
elif nb_of_knights == 1:
print(f'At least 1 chess knight has explored this board.')
else:
print(f'At least {nb_of_knights} chess knights have explored this board')