AcWing 756. 蛇形矩阵 python3
原题链接
简单
from typing import List
class Solution:
def __init__(self):
pass
def draw(self, row: int, col: int) -> List[List[str]]:
# 方向:右下左上
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
pic = [['-1' for _ in range(col)] for _ in range(row)]
x, y, d = 0, 0, 0
num = 1
while True:
if num==col*row+1: break
# 先把数填上
pic[x][y] = str(num)
num += 1
# 计算下一个方向
a = x+dx[d]; b = y+dy[d]
# 判断下一个方向是否合法
if a>=0 and a<row and b>=0 and b<col and pic[a][b]=='-1': # 合法
pass
else:
d = (d+1)%4
a = x+dx[d]; b = y+dy[d]
x = a; y = b
return pic
if __name__ == '__main__':
row, col = map(int, input().split())
solution = Solution()
res = solution.draw(row, col)
a = [' '.join(_) for _ in res]
for _ in a:
print(_)