题解 | #回型矩阵#

回型矩阵

http://www.nowcoder.com/practice/36d5dfddc22c4f5b88a5b2a9de7db343

有限状态机

n = int(input())

s=[[-1 for i in range(n)] for i in range(n)]
cnt=0
direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]
# 0 1 = right
# 1 0 = down
# 0 -1 = left
# -1 0 = up
x, y=0, 0
state = 0
trace = []
for i in range(n**2):
        cnt+=1
        s[y][x]=cnt
        # 记录已经经过的轨迹 
        trace.append([y, x])
        y+=direction[state%4][0]
        x+=direction[state%4][1]
        if ([y, x] in trace) or y>=n or y<0 or x>=n or x<0:
            # 越界或者已经经过,回退坐标
            y-=direction[state%4][0]
            x-=direction[state%4][1]
            # 更新状态
            state+=1
            # 更新坐标
            y+=direction[state%4][0]
            x+=direction[state%4][1]

for i in s:
    for j in i:
        print(j, end=' ')
    print()
全部评论

相关推荐

joecii:如果没有工资,那可能没有工资是这家公司最小的问题了
找实习记录
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务