สมมติให้มีเมทริกซ์สี่เหลี่ยมจัตุรัสขนาด N×N งานคือการหมุนเมทริกซ์ทิศตรงข้ามเข็มนาฬิกา (counterclockwise) 90 องศา
ตัวอย่าง Input-1
N = 3
matrix[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Output
3 6 9 2 5 8 1 4 7
แนวทางแก้ปัญหา
วิธีที่ง่ายที่สุดคือ:
- หา Transpose ของเมทริกซ์ (สลับแถวกับคอลัมน์)
- กลับลำดับคอลัมน์ (swap คอลัมน์แรกกับคอลัมน์สุดท้าย, คอลัมน์ที่ 2 กับ倒数ที่ 2, ...)
เหตุผล: การหมุน 90 องศา CCW = Transpose + Horizontal Flip (กลับซ้าย-ขวา)
ตัวอย่างโค้ด
import java.io.*;
class Solution {
static void rotateMatrix(int n, int[][] matrix) {
// ขั้นตอนที่ 1: หา Transpose
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// ขั้นตอนที่ 2: กลับลำดับคอลัมน์ (swap column 0 กับ n-1, 1 กับ n-2, ...)
for (int i = 0; i < n; i++) {
int top = 0;
int bottom = n - 1;
while (top < bottom) {
int temp = matrix[top][i];
matrix[top][i] = matrix[bottom][i];
matrix[bottom][i] = temp;
top++;
bottom--;
}
}
}
static void displayMatrix(int n, int[][] mat) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(" " + mat[i][j]);
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
int N = 3;
int[][] mat = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
rotateMatrix(N, mat);
displayMatrix(N, mat);
}
}
ผลลัพธ์
3 6 9 2 5 8 1 4 7
หมายเหตุเพิ่มเติม
- หากต้องการหมุน 90 องศา ตามเข็มนาฬิกา (CW): Transpose + Vertical Flip (กลับบน-ล่าง)
- Time Complexity: O(N²) - ต้องเข้าถึงทุกเซลล์
- Space Complexity: O(1) - ทำ in-place