思路
1. 一圈圈的打印,开始点为左上角(0,0)
1. 第一圈:(0,0)
2. 第二圈:(1,1)
3. 第N圈:(n,n)
2. 总共可以打印多少圈,n为行与列的一半,超出就终止
python实现
def print_one_circle(array_input, rows, cols, start): ret = [] if len(array_input) == 0: return ret # 列数 end_x = cols - 1 - start # 行数 end_y = rows - 1 - start # 从左往右打印 for i in range(start, end_x+1): ret.append(array_input[start][i]) # 从上往下打印 if start < end_y: for i in range(start+1, end_y+1): ret.append(array_input[i][end_x]) # 从右往左打印 if start < end_y and start < end_x: for i in range(end_x - 1, start-1, -1): ret.append(array_input[end_y][i]) # 从下往上打印 if start < end_y - 1 and start < end_x: for i in range(end_y - 1, start, -1): ret.append(array_input[i][start]) return ret def print_matrix(array_input): ret = [] if len(array_input) == 0: return ret rows = len(array_input) cols = len(array_input[0]) start = 0 while rows > 2*start and cols > 2*start: tmp = print_one_circle(array_input, rows, cols, start) ret += tmp start += 1 return ret if __name__ == "__main__": array_input = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print(print_matrix(array_input))