1. 程式人生 > >劍指offer19.順時針列印矩陣

劍指offer19.順時針列印矩陣

https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

輸入一個矩陣,按照從外向裡以順時針的順序依次打印出每一個數字,例如,如果輸入如下4 X 4矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 則依次打印出數字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

可以對四個角點做標記,然後從左到右,從上到下,從右到左,從下到上遍歷一個圈,考慮到可能存在奇數行或列,所以要對top和bottom以及left和right做一個判斷,標記內縮一圈:

# -*- coding:utf-8 -*-
class Solution:
    # matrix型別為二維列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        res = []
        if not matrix or not matrix[0]:
            return res
        left,
right, top, bottom = 0, len(matrix[0])-1, 0, len(matrix)-1 while left <= right and top <= bottom: for j in range(left, right+1): res.append(matrix[top][j]) for i in range(top+1, bottom+1): res.append(matrix[i][right]) if
top < bottom: for j in range(right-1, left, -1): res.append(matrix[bottom][j]) if left < right: for i in range(bottom,top, -1): res.append(matrix[i][left]) left += 1 right -= 1 top += 1 bottom -= 1 return res

還有種思路就是,每取一行,matrix就逆時針旋轉90度,直到為空:

# -*- coding:utf-8 -*-
class Solution:
    # matrix型別為二維列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        res = []
        while matrix:
            res.extend(matrix.pop(0))
            if not matrix or not matrix[0]:
                break
            matrix = self.rotate(matrix)
        return res

    def rotate(self, mat):
        new = []
        for j in range(len(mat[0])-1, -1, -1):
            new.append([row[j] for row in mat])
        return new