Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมพิมพ์สมาชิกเมทริกซ์แบบเกลียวใน Python


มีเมทริกซ์ 2D พิมพ์สมาชิกแบบเกลียว: แถวแรกซ้ายขวา, คอลัมน์สุดท้ายบนล่าง, แถวสุดท้ายขวาซ้าย, คอลัมน์แรกล่างบน, ทำซ้ำ

เช่น เมทริกซ์ 6x3 ให้ [7,10,9,1,3,4,5,11,9,9,2,9,6,2,9,2,1,7]

ขั้นตอนการแก้ปัญหา

  • กำหนดขอบเขต top, down, left, right และ direction (0=ขวา,1=ลง,2=ซ้าย,3=ขึ้น)
  • วนจน top<=down and left<=right:
    • ตาม direction พิมพ์ขอบและหดขอบเขต
    • direction = (direction+1)%4

ตัวอย่างโค้ด

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
            elif direction == 1:
                for i in range(top, down+1): res.append(matrix[i][right])
                right -= 1
            elif direction == 2:
                for i in range(right, left-1, -1): res.append(matrix[down][i])
                down -= 1
            else:
                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]