順時針打印矩陣
題目描述
輸入一個矩陣,按照從外向里以順時針的順序依次打印出每一個數(shù)字礼仗,例如绿满,如果輸入如下4 X 4矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 則依次打印出數(shù)字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
思路
- 對于方陣,可以通過順時針遍歷每一層的方式坯钦,逐層遍歷蟀苛,得到結果
可以想到益咬,對于最外層,只需要順時針遍歷四條邊即可屹逛,但對于里層础废,就不那么好處理了
此時,按照從外層到內層的方向罕模,每遍歷一行/一列,都將這一行/列從矩陣中刪去,依次來保證遍歷每一層時帘瞭,這一層都在矩陣的最外層淑掌。
遍歷過的每一行/列的刪除操作,不必真的刪除蝶念,只需要設定四個指針(行起始抛腕,行終止,列起始媒殉,列終止)担敌,遍歷一行后,移動響應的指針即可廷蓉。
這樣全封,循環(huán)終止的條件就可以設定為:行終止-行起始 == 0 || 列終止-列起始==0 - 而對于非方陣:
在方陣中,(行終止-行起始 == 0)桃犬,(列終止-列起始==0)一定是同時達到的刹悴,而對于非方陣,這兩個結束條件一定有一個比另個一個先達到攒暇,所以此時土匀,應該在循環(huán)中加上條件判斷,讓循環(huán)提前跳出形用。
# -*- coding:utf-8 -*-
class Solution:
# matrix類型為二維列表就轧,需要返回列表
def printMatrix(self, matrix):
# write code here
row_min,col_min,row_max,col_max = 0,0,len(matrix),len(matrix[0])
list = []
while row_max-row_min > 0 and col_max-col_min > 0 :
i = row_min
for j in range(col_min,col_max):
list.append(matrix[i][j])
row_min += 1
if not row_max-row_min > 0 or not col_max-col_min > 0 :
break
j = col_max-1
for i in range(row_min,row_max):
list.append(matrix[i][j])
col_max -= 1
if not row_max - row_min > 0 or not col_max - col_min > 0:
break
i = row_max-1
for j in range(col_min,col_max)[::-1]:
list.append(matrix[i][j])
row_max -= 1
if not row_max - row_min > 0 or not col_max - col_min > 0:
break
j = col_min
for i in range(row_min,row_max)[::-1]:
list.append(matrix[i][j])
col_min += 1
if not row_max - row_min > 0 or not col_max - col_min > 0:
break
return list