สมมติว่าเรามีเมทริกซ์ 2D ที่แทนภาพ เราต้องหมุนภาพนี้ 90 องศาในทิศทางเข็มนาฬิกา (clockwise) ตัวอย่าง ภาพเป็น:
| 1 | 5 | 7 |
| 9 | 6 | 3 |
| 2 | 1 | 3 |
ผลลัพธ์จะเป็น:
| 2 | 9 | 1 |
| 1 | 6 | 5 |
| 3 | 3 | 7 |
ขั้นตอนการทำงาน
- พิจารณา
temp_mat = [],col := len(matrix) - 1 - วนลูป
colจาก 0 ถึงlen(matrix)-1:temp := []- วนลูป
rowจากlen(matrix)-1ลงถึง0:- เพิ่ม
matrix[row][col]ลงtemp
- เพิ่ม
- เพิ่ม
tempลงtemp_mat
- คัดลอก
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]]