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

Rotate Image ใน Python - หมุนเมทริกซ์ 90 องศา

สมมติว่าเรามีเมทริกซ์ 2D ที่แทนภาพ เราต้องหมุนภาพนี้ 90 องศาในทิศทางเข็มนาฬิกา (clockwise) ตัวอย่าง ภาพเป็น:

157
963
213

ผลลัพธ์จะเป็น:

291
165
337

ขั้นตอนการทำงาน

  1. พิจารณา temp_mat = [], col := len(matrix) - 1
  2. วนลูป col จาก 0 ถึง len(matrix)-1:
    • temp := []
    • วนลูป row จาก len(matrix)-1 ลงถึง 0:
      • เพิ่ม matrix[row][col] ลง temp
    • เพิ่ม temp ลง temp_mat
  3. คัดลอก temp_mat กลับไป matrix

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

class Solution(object):
    def rotate(self, matrix):
        temp_matrix = []
        column = len(matrix) - 1
        for column in range(len(matrix)):
            temp = []
            for row in range(len(matrix) - 1, -1, -1):
                temp.append(matrix[row][column])
            temp_matrix.append(temp)
        for i in range(len(matrix)):
            for j in range(len(matrix)):
                matrix[i][j] = temp_matrix[i][j]
        return matrix

ob1 = Solution()
print(ob1.rotate([[1,5,7],[9,6,3],[2,1,3]]))

อินพุต

[[1,5,7],[9,6,3],[2,1,3]]

เอาต์พุต

[[2,9,1],[1,6,5],[3,3,7]]