题目描述:
棋盘上A点有一个过河卒,需要走到目标B点。卒行走的规则:可以向下、或者向右。同时在棋盘上C点有一个对方的马,该马所在的点和所有跳跃一步就可达的点称为对方马的控制点。因此称之为“马拦过河卒”。
棋盘用坐标表示,A点(0,0)、B点(n,m),同样马的位置坐标是需要给出的。
计算出卒从A点能够到达B点的路径条数,假设马的位置是固定不动的,并不是卒走一步马走一步。
import numpy as np
x = input("请输入请输入棋盘的行和列:").split()
y = input("请输入马所在的横坐标和纵坐标:").split()
a = int(x[0])
b = int(x[1])
hx = int(y[0])
hy = int(y[1]) # 强制类型转换
if hx + 2 >= a or hy + 2 >= b or hx - 2 < 0 or hy - 2 < 0: # 判断马跳跃的位置是否越界
print("输入错误,请重新输入。")
else:
chessboard = np.zeros((a, b)) # 生成a行b列的含零数组。
chessboard = chessboard.astype('int') # 浮点数转换为整数,小数点后的部分被删除
chessboard[0, 0] = 1
chessboard[hx, hy] = -2
chessboard[hx+1, hy+2] = chessboard[hx+1, hy-2] = chessboard[hx-1, hy+2] = chessboard[hx-1, hy-2] = -1
chessboard[hx+2, hy+1] = chessboard[hx+2, hy-1] = chessboard[hx-2, hy+1] = chessboard[hx-2, hy-1] = -1
for i in range(0, a):
for j in range(0, b):
if chessboard[i][j] < 0:
continue
if chessboard[i][j - 1] > 0:
chessboard[i][j] += chessboard[i][j - 1]
if chessboard[i - 1][j] > 0:
chessboard[i][j] += chessboard[i - 1][j]
print(chessboard)
print(f"从A点能够到达B点的路径的条数为{chessboard[a - 1, b - 1]}")
代码运行结果: