参考代码:
def opt(i): global x,y,lst,step #这里需要注意一下,当到达每行或者每列的边界时,由于主程序中循环的边界问题未能将边界元素添加进去,所以放在函数中处理 lst.append(board[x][y]) step = step + 1 #定义四种操作,这四种操作其实就是连续左转九十度 if i%4==1: x, y = x, y + 1 elif i%4==2: x,y=x-1,y elif i%4==3: x,y=x,y-1 elif i%4==0: x,y=x+1,y while True: try: m,n=map(int,input().split()) board=[] for i in range(m): board.append(input().split()) lst=list() x,y=0,0#当前坐标 step=0#计步器 choice=1#操作选择器 du,dd,dl,dr=0,m-1,0,n-1#在四种操作轮替之间的边界定夺,可以如此理解:例如说,首先是竖直向下并入矩阵中的元素,当并入一列之后,这一列就相当于把原来的边界m*n变成了m*(n-1),这时dl也就是左边界会加一,du、dd、dl、dr分别对应的是上边界、下边界、右边界 while step!=n*m: if choice % 4 == 1: while x != dd: lst.append(board[x][y]) x = x + 1 step = step + 1 dl = dl + 1 opt(choice) choice += 1 elif choice % 4 == 2: while y != dr: lst.append(board[x][y]) y = y + 1 step = step + 1 dd = dd - 1 opt(choice) choice += 1 elif choice % 4 == 3: while x != du: lst.append(board[x][y]) x = x - 1 step = step + 1 dr = dr - 1 opt(choice) choice += 1 elif choice % 4 == 0: while y != dl: lst.append(board[x][y]) y = y - 1 step = step + 1 du = du + 1 opt(choice) choice += 1 for item in lst: print(int(item),end=' ') except: break
0.0分
0 人评分