การหมุนเมทริกซ์ 90 องศาตามเข็มนาฬิกา
โจทย์
Given an matrix, write a program that reads the matrix as input and rotates it by 90 degrees clockwise. Finally, print the rotated matrix.
Input:
- The first line of input contains an integer N (the number of rows and columns of the matrix).
- The next N lines contain N space-separated integers representing the matrix.
Output:
- Print the matrix after rotating it by 90 degrees clockwise.
| Input | Output |
|---|---|
| 3 1 2 3 4 5 6 7 8 9 | 7 4 1 8 5 2 9 6 3 |
โค้ด
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[n - j - 1][i] + " ");
}
System.out.println();
}
}
}คำอธิบาย
1. การประกาศคลาสและการรับข้อมูล
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();- สร้างคลาส
Program - ใช้
Scannerเพื่อรับข้อมูลจากผู้ใช้ - รับค่า N ซึ่งเป็นขนาดของเมทริกซ์
2. การสร้างและเก็บข้อมูลเมทริกซ์
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
}
}- สร้างอาร์เรย์ 2 มิติขนาด n x n
- ใช้ลูปซ้อนเพื่อรับค่าตัวเลขเข้าเมทริกซ์
iคือแถว,jคือคอลัมน์
3. การหมุนและแสดงผลเมทริกซ์
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[n - j - 1][i] + " ");
}
System.out.println();
}- ใช้สูตร
matrix[n - j - 1][i]เพื่อหมุนเมทริกซ์ n - j - 1คือการกลับลำดับแถวiกลายเป็นคอลัมน์ใหม่
แผนภาพการทำงาน
ปรับปรุงล่าสุด