def fenge(i, j): if i == j&nbs***bsp;i + j == N-1&nbs***bsp;N % 2 != 0 and int(N/2)== i&nbs***bsp;N % 2 != 0 and int(N/2)== j: return True return False N = int(input()) matric = [[0 for col in range(N)] for row in range(N)] row_start = 0 row_end = N - 1 col_start = 0 col_end = N - 1 index = 1 while row_start <= row_end and col_start <= col_end: # 上 i = row_start j = col_end while j >= col_start: if fenge(i, j) == False: matric[i][j] = index index += 1 j -= 1 # 左 i = row_start + 1 j = col_start while i < row_end: if fenge(i, j) == False: matric[i][j] = index index += 1 i += 1 # 下 i = row_end j = col_start while j <= col_end: if fenge(i, j) == False: matric[i][j] = index index += 1 j += 1 # 右 i = row_end - 1 j = col_end while i > row_start: if fenge(i, j) == False: matric[i][j] = index index += 1 i -= 1 row_start += 1 row_end -= 1 col_start += 1 col_end -= 1 for row in range(N): string = "" for col in range(N): string += str(matric[row][col]) + " " string.strip() print(string)
代码如上,本地测试两个样例都对了
全部评论
(5) 回帖