Python程式:螺旋順序列印矩陣元素
假設我們有一個二維矩陣mat。我們需要以螺旋的方式列印矩陣元素。首先從第一行(mat[0, 0])開始,列印整個內容,然後沿著最後一列列印,然後是最後一行,依此類推,從而以螺旋的方式列印元素。
因此,如果輸入如下所示:
| 7 | 10 | 9 |
| 2 | 9 | 1 |
| 6 | 2 | 3 |
| 9 | 1 | 4 |
| 2 | 7 | 5 |
| 9 | 9 | 11 |
則輸出將為 [7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]
為了解決這個問題,我們將遵循以下步驟
- d := 0
- top := 0, down := 矩陣的行數 – 1, left := 0, right := 矩陣的列數 - 1
- c := 0
- res := 一個新的列表
- direction := 0
- 當 top <= down 且 left <= right 時,執行以下操作
- 如果 direction 等於 0,則
- 對於 i 從 left 到 right + 1,執行以下操作
- 將 matrix[top, i] 插入 res
- top := top + 1
- 對於 i 從 left 到 right + 1,執行以下操作
- 如果 direction 等於 1,則
- 對於 i 從 top 到 down + 1,執行以下操作
- 將 matrix[i, right] 插入 res
- right := right - 1
- 對於 i 從 top 到 down + 1,執行以下操作
- 如果 direction 等於 2,則
- 對於 i 從 right 到 left - 1,遞減 1,執行以下操作
- 將 matrix[down, i] 插入 res
- down := down - 1
- 對於 i 從 right 到 left - 1,遞減 1,執行以下操作
- 如果 direction 等於 3,則
- 對於 i 從 down 到 top - 1,遞減 1,執行以下操作
- 將 matrix[i, left] 插入 res
- left := left + 1
- 對於 i 從 down 到 top - 1,遞減 1,執行以下操作
- 如果 direction 等於 0,則
- direction :=(direction + 1) mod 4
- 返回 res
讓我們看看以下實現,以便更好地理解
示例
class Solution: def solve(self, matrix): d = 0 top = 0 down = len(matrix) - 1 left = 0 right = len(matrix[0]) - 1 c = 0 res = [] direction = 0 while top <= down and left <= right: if direction == 0: for i in range(left, right + 1): res.append(matrix[top][i]) top += 1 if direction == 1: for i in range(top, down + 1): res.append(matrix[i][right]) right -= 1 if direction == 2: for i in range(right, left - 1, -1): res.append(matrix[down][i]) down -= 1 if direction == 3: for i in range(down, top - 1, -1): res.append(matrix[i][left]) left += 1 direction = (direction + 1) % 4 return res ob = Solution() matrix = [ [7, 10, 9], [2, 9, 1], [6, 2, 3], [9, 1, 4], [2, 7, 5], [9, 9, 11] ] print(ob.solve(matrix))
輸入
[ [7, 10, 9],[2, 9, 1],
[6, 2, 3],[9, 1, 4],
[2, 7, 5],[9, 9, 11]
]
輸出
[7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP