Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. [#54]
Example 1: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5] Example 2: Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
题意:按螺旋顺序返回指定m行n列矩阵的所有元素
递归法:
def func(t): if len(t)==1: return t[0] elif len(t)==2: return t[0]+t[1][::-1] else: r = [] r.extend(t[0]) for i in range(1,len(t)): if i+1 == len(t): r.extend(t.pop()[::-1]) else: r.append(t[i].pop()) t=t[1:] if t[0]==[]: return r for i in reversed(range(1,len(t))): r.append(t[i][0]) t[i]=t[i][1:] return r+func(t) t = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] print(func(t)) t = [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] print(func(t)) # 其他测试 t = [ [1,2,3,4] ] print(func(t)) t = [ [1,2,3,4], [8,7,6,5] ] print(func(t)) t = [ [1], [2], [3], [4] ] print(func(t)) t = [ [1,2], [8,3], [7,4], [6,5] ] print(func(t)) t = [ [1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7] ] print(func(t)) t = [ [1, 2, 3, 4], [14, 15, 16, 5], [13, 20, 17, 6], [12, 19, 18, 7], [11, 10, 9, 8], ] print(func(t)) ''' 测试结果: [1, 2, 3, 6, 9, 8, 7, 4, 5] [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] [1, 2, 3, 4] [1, 2, 3, 4, 5, 6, 7, 8] [1, 2, 3, 4] [1, 2, 3, 4, 5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] '''
Spiral Matrix II
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. [#59]
Example: Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]