Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình in ma trận theo thứ tự xoắn ốc bằng Python


Cho ma trận 2D. In các phần tử theo thứ tự xoắn ốc: hàng đầu → cột cuối → hàng cuối → cột đầu → lặp lại.

Ví dụ: ma trận 6x3 → danh sách 18 phần tử theo xoắn ốc.

Giải thuật

  • Giới hạn 4 biên: top, down, left, right.
  • Biến direction (0: trái→phải, 1: trên→dưới, 2: phải→trái, 3: dưới→trên).
  • Lặp khi top <= down and left <= right:
    • Theo direction duyệt biên tương ứng, thêm vào kết quả, thu hẹp biên.
    • direction = (direction+1)%4.

Ví dụ minh họa

class Solution:
    def solve(self, matrix):
        top = 0
        down = len(matrix) - 1
        left = 0
        right = len(matrix[0]) - 1
        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))

Đầu vào

[[7,10,9],[2,9,1],[6,2,3],[9,1,4],[2,7,5],[9,9,11]]

Đầu ra

[7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]