劍指offer:順時針打印矩陣(Python)

題目描述

輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下矩陣: 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.

解題思路

重新描述一下題意:
輸入矩陣:

01 02 03 04
05 06 07 08
09 10 11 12
13 14 15 16

需要依次打印出1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

思路1

時刻定位矩陣的左上角索引座標和右下角索引座標。當順時針轉完一圈之後,左上角的橫縱索引各自加一;右下角的橫縱索引各自減一。注意當左上角索引和右下角索引到達同一行/同一列時的情況。

def printMatrix(self, matrix):
    x0 = y0 = 0
    xn = len(matrix)-1
    yn = len(matrix[0])-1
    list = []
    while x0<=xn and y0<=yn:
        for y in range(y0, yn+1):
            list.append(matrix[x0][y])
        for x in range(x0+1, xn+1):
            list.append(matrix[x][yn])
        if x0 < xn:
            for y in range(yn-1, y0-1, -1):
                list.append(matrix[xn][y])
        if y0 < yn:
            for x in range(xn-1, x0, -1):
                list.append(matrix[x][y0])
        x0 += 1
        y0 += 1
        xn -= 1
        yn -= 1
    return list

思路2

我用的語言是Python!意味着也許Java和C++需要取巧才能得到答案的時候,Python可以不講理的硬上,無腦暴力但又優美的解決…比如這道題:

def printMatrix(self, matrix):
    res = []
    while matrix:
        res += matrix.pop(0)
        if matrix and matrix[0]:
            for row in matrix:
                res.append(row.pop())
        if matrix:
            res += matrix.pop()[::-1]
        if matrix and matrix[0]:
            for row in matrix[::-1]:
                res.append(row.pop(0))
    return res

有的時候,甚至懷疑,用Python練習編程題到底是不是個好主意… 因爲跳過了出題人的期待,三下五除二得到答案,結果沒有很好地練到手…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章