很明显,我们针对4个起点 2个方向,应该有8组测试案例
现在您的代码 只能通过4组,还有另外的4组案例 无法通过
def generate_snake_matrix(size, start_point, direction):
matrix = [[0 for _ in range(size)] for _ in range(size)] # 创建一个空的矩阵
x, y = start_point # 获取起点坐标
num = 1 # 要填充的数字
while True:
matrix[y][x] = num # 填充当前位置的数字
if direction == 'down':
if y + 1 < size and matrix[y+1][x] == 0: # 向下移动
y += 1
elif x + 1 < size and matrix[y][x+1] == 0: # 向右移动
x += 1
direction = 'right'
else:
break
elif direction == 'right':
if x + 1 < size and matrix[y][x+1] == 0: # 向右移动
x += 1
elif y - 1 >= 0 and matrix[y-1][x] == 0: # 向上移动
y -= 1
direction = 'up'
else:
break
elif direction == 'up':
if y - 1 >= 0 and matrix[y-1][x] == 0: # 向上移动
y -= 1
elif x - 1 >= 0 and matrix[y][x-1] == 0: # 向左移动
x -= 1
direction = 'left'
else:
break
elif direction == 'left':
if x - 1 >= 0 and matrix[y][x-1] == 0: # 向左移动
x -= 1
elif y + 1 < size and matrix[y+1][x] == 0: # 向下移动
y += 1
direction = 'down'
else:
break
num += 1
return matrix
# 测试1
size = 6 # 矩阵的大小
start_point = (0, 0) # 起点坐标
direction = 'down' # 初始方向
snake_matrix = generate_snake_matrix(size, start_point, direction)
# 输出蛇形矩阵
for row in snake_matrix:
for num in row:
print(str(num).rjust(2), end=' ')
print()
# 测试2
size = 6 # 矩阵的大小
start_point = (0, 0) # 起点坐标
direction = 'right' # 初始方向
snake_matrix = generate_snake_matrix(size, start_point, direction)
# 输出蛇形矩阵
for row in snake_matrix:
for num in row:
print(str(num).rjust(2), end=' ')
print()
# 测试3
size = 6 # 矩阵的大小
start_point = (0, 5) # 起点坐标
direction = 'down' # 初始方向
snake_matrix = generate_snake_matrix(size, start_point, direction)
# 输出蛇形矩阵
for row in snake_matrix:
for num in row:
print(str(num).rjust(2), end=' ')
print()
# 测试4
size = 6 # 矩阵的大小
start_point = (0, 5) # 起点坐标
direction = 'left' # 初始方向
snake_matrix = generate_snake_matrix(size, start_point, direction)
# 输出蛇形矩阵
for row in snake_matrix:
for num in row:
print(str(num).rjust(2), end=' ')
print()
# 测试5
size = 6 # 矩阵的大小
start_point = (5, 5) # 起点坐标
direction = 'left' # 初始方向
snake_matrix = generate_snake_matrix(size, start_point, direction)
# 输出蛇形矩阵
for row in snake_matrix:
for num in row:
print(str(num).rjust(2), end=' ')
print()
# 测试6
size = 6 # 矩阵的大小
start_point = (5, 5) # 起点坐标
direction = 'up' # 初始方向
snake_matrix = generate_snake_matrix(size, start_point, direction)
# 输出蛇形矩阵
for row in snake_matrix:
for num in row:
print(str(num).rjust(2), end=' ')
print()
# 测试7
size = 6 # 矩阵的大小
start_point = (5, 0) # 起点坐标
direction = 'right' # 初始方向
snake_matrix = generate_snake_matrix(size, start_point, direction)
# 输出蛇形矩阵
for row in snake_matrix:
for num in row:
print(str(num).rjust(2), end=' ')
print()
# 测试8
size = 6 # 矩阵的大小
start_point = (5, 0) # 起点坐标
direction = 'up' # 初始方向
snake_matrix = generate_snake_matrix(size, start_point, direction)
# 输出蛇形矩阵
for row in snake_matrix:
for num in row:
print(str(num).rjust(2), end=' ')
print()
|