題目:假定有一個二維數(shù)組烈掠,要求將數(shù)組中的元素以順時針的旋轉(zhuǎn)方式打印出來羞秤。實現(xiàn)一個函數(shù),使得數(shù)組的元素能按照順時針方向打印左敌。
分析:假定有4個箭頭锥腻,分別稱為top,right母谎,bottom瘦黑,left。top指向最頂行奇唤,right指向最右邊一列幸斥,bottom指向最底邊一行,left指向最左邊一列咬扇。先把top指向的行打印出來甲葬,接著把right指向的列打印出來,然后把bottom指向的行打印出來懈贺,最后把left指向的列打印出來经窖。然后把外圍打印完畢后,把top箭頭向下挪動一個位置梭灿,right箭頭向左挪動一個位置画侣,bottom向上挪動一個位置,left向右挪動一個位置堡妒。
code:
def spiralPrint(top, right, bottom, left):
? ? while top <= bottom and left <= right:
? ? ? ? # 先打印top指向的行
? ? ? ? for i in range(left, right + 1):
? ? ? ? ? ? print(array[top][i])
? ? ? ? # 打印right指向的行
? ? ? ? for i in range(top + 1, bottom + 1):
? ? ? ? ? ? print(array[i][right])
? ? ? ? # 打印bottom指向的行
? ? ? ? for i in range(bottom - 1, left - 1, -1):
? ? ? ? ? ? print(array[bottom][i])
? ? ? ? for i in range(bottom - 1, top, -1):
? ? ? ? ? ? print(array[i][left])
? ? ? ? top += 1
? ? ? ? right -= 1
? ? ? ? bottom -= 1
? ? ? ? left += 1
if __name__ == "__main__":
? ? n = 5
? ? array = [[0] * n for i in range(n)]
? ? for i in range(n):
? ? ? ? for j in range(n):
? ? ? ? ? ? array[i][j] = i * n + j + 1
? ? ? ? print(array[i])
? ? top = 0
? ? right = n - 1
? ? bottom = n - 1
? ? left = 0
? ? spiralPrint(top, right, bottom, left)