用蛇的方式浏览2D列表

时间:2017-02-08 19:23:54

标签: list python-3.x

我有一个大小为n的2D方形列表。我的目的是以蛇的形状穿过它。例如:

array = [[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]

对于这种情况,结果应为[1, 2, 3, 6, 9, 8, 7, 4, 5]

1 个答案:

答案 0 :(得分:0)

def spiral_array(arr):
        if arr == []: return []
        up = 0; left = 0
        down = len(arr)-1
        right = len(arr[0])-1
        direct = 0  # 0: go right   1: go down  2: go left  3: go up
        res = []
        while True:
            if direct == 0:
                for i in range(left, right+1):
                    res.append(arr[up][i])
                up += 1
            if direct == 1:
                for i in range(up, down+1):
                    res.append(arr[i][right])
                right -= 1
            if direct == 2:
                for i in range(right, left-1, -1):
                    res.append(arr[down][i])
                down -= 1
            if direct == 3:
                for i in range(down, up-1, -1):
                    res.append(arr[i][left])
                left += 1
            if up > down or left > right: return res
            direct = (direct+1) % 4

array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print(spiral_array(array)) # [1, 2, 3, 6, 9, 8, 7, 4, 5]

来源:https://leetcode.com/problems/spiral-matrix/