Skip to Content
CoursesCSC102การหมุนเมทริกซ์ 180 องศา

การหมุนเมทริกซ์ 180 องศา

โจทย์

Write a Java program that rotates a matrix by 180 degrees. The program should accept matrix dimensions and elements as input and print the rotated matrix as output. Ensure your solution is in place and does not use extra space beyond what is necessary for swapping the elements.

Input:

  • First line contains row and column of the matrix
  • Second line are the members of the matrix

Output:

  • After rotation 180 degree of the matrix
InputOutput
3 3
1 2 3
4 5 6
7 8 9
9 8 7
6 5 4
3 2 1

โค้ด

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = scanner.nextInt(); } } for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }

คำอธิบาย

1. การประกาศคลาสและรับขนาดเมทริกซ์

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); // จำนวนแถว int m = scanner.nextInt(); // จำนวนคอลัมน์

2. การสร้างและรับข้อมูลเมทริกซ์

int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { matrix[i][j] = scanner.nextInt(); } }
  • สร้างเมทริกซ์ 2 มิติขนาด n × m
  • ใช้ loop ซ้อนเพื่อรับค่าข้อมูลทีละตำแหน่ง

3. การแสดงผลเมทริกซ์ที่หมุน 180 องศา

for (int i = n - 1; i >= 0; i--) { // วนลูปจากแถวสุดท้ายไปแถวแรก for (int j = m - 1; j >= 0; j--) { // วนลูปจากคอลัมน์สุดท้ายไปคอลัมน์แรก System.out.print(matrix[i][j] + " "); } System.out.println(); }
  • วนลูปแบบย้อนกลับทั้งแถวและคอลัมน์
  • แสดงผลแต่ละสมาชิกพร้อมเว้นวรรค
  • ขึ้นบรรทัดใหม่เมื่อจบแต่ละแถว

แผนภาพการทำงาน

การหมุนเมทริกซ์ 180 องศา

ตัวอย่างเมทริกซ์ 3×33 \times 3:

เมทริกซ์ต้นฉบับ: เมทริกซ์ที่หมุนแล้ว: 1 2 3 9 8 7 4 5 6 → 6 5 4 7 8 9 3 2 1

วิธีการเข้าถึงสมาชิก:

ต้นฉบับ [i][j]: หมุนแล้ว [n-1-i][m-1-j]: [0,0] [0,1] [0,2] [2,2] [2,1] [2,0] [1,0] [1,1] [1,2] → [1,2] [1,1] [1,0] [2,0] [2,1] [2,2] [0,2] [0,1] [0,0]

ตัวอย่างการทำงาน

ตัวอย่างที่ 1

Input: 3 3 1 2 3 4 5 6 7 8 9 Output: 9 8 7 6 5 4 3 2 1

ตัวอย่างที่ 2

Input: 2 4 1 2 3 4 5 6 7 8 Output: 8 7 6 5 4 3 2 1
ปรับปรุงล่าสุด