dir = [(1, 0), (0, 1), (-1, 0), (0, -1)] #4个方向 m, n = map(int, input().split()) a = [] for i inrange(m): a.append(input().split()) x, y = -1, 0 d = 0 sum = 0 whilesum < m*n: sum = sum + 1 nx, ny = x + dir[d][0], y + dir[d][1] if nx < 0or nx >= m or ny < 0or ny >= n or a[nx][ny]==-1: d = (d + 1) % 4 x, y = x + dir[d][0], y + dir[d][1] else: x, y = nx, ny print(a[x][y], end=' ') a[x][y] = -1#标记这个坐标点已经取过
对代码的解释
初始化方向数组
dir = [(1, 0), (0, 1), (-1, 0), (0, -1)] # 4个方向
这里定义了一个方向数组,表示右、下、左、上四个方向。
输入矩阵的行数和列数
m, n = map(int, input().split())
输入矩阵的元素
a = [] for i inrange(m): a.append(input().split())
whilesum < m*n: sum = sum + 1 nx, ny = x + dir[d][0], y + dir[d][1] if nx < 0or nx >= m or ny < 0or ny >= n or a[nx][ny]==-1: d = (d + 1) % 4 x, y = x + dir[d][0], y + dir[d][1] else: x, y = nx, ny print(a[x][y], end=' ') a[x][y] = -1