Skip to Content
CoursesCSC102การสร้างเมทริกซ์แบบหมุนวน (Spinning Matrix)

การสร้างเมทริกซ์แบบหมุนวน (Spinning Matrix)

โจทย์

You are tasked with writing a program that generates a matrix spinning according to the given input of rows and columns.

Input:

  • An integer of row (1\<=n\<=501 \<= n \<= 50) represents the number of rows in the pattern.
  • An integer of column (1\<=n\<=501 \<= n \<= 50) represents the number of columns in the pattern.
  • row×columnrow \times column should not be greater than or equal to 100 (i.e., rowscolumn<100rows * column < 100).

Output:

  • A spinning Matrix is given above.
InputOutput
3 41 2 3 4
10 11 12 5
9 8 7 6
4 41 2 3 4
16 15 14 5
11 12 13 6
10 9 8 7

Explanation:

1 -> 2 -> 3 -> 4 | 10 -> 11 -> 12 5 | | 9 <- 8 <- 7 <- 6
1 -> 2 -> 3 -> 4 | 16 <- 15 <- 14 5 | | 11 -> 12 -> 13 6 | | 10 <- 9 <- 8 <- 7

โค้ด

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int rows = scanner.nextInt(); int cols = scanner.nextInt(); int currentNumber = 1; int[][] matrix = new int[rows][cols]; int direction = 0; int x = 0, y = 0; int borderBottom = 0; while (currentNumber <= rows * cols) { matrix[y][x] = currentNumber; switch (direction % 4) { case 0: //Right x++; if (x == cols - 1 && y == 0 || x == cols - 2 && y > 0) { direction = (y > 0) ? 3 : 1; } break; case 1: //Down y++; if (y == rows - 1) direction++; break; case 2: //Left x--; if (x == 0) direction = 3; break; case 3: //Up y--; direction = (borderBottom % 2 == 0) ? 0 : 2; borderBottom++; break; } currentNumber++; } for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }

คำอธิบาย

1. การเตรียมข้อมูล

int currentNumber = 1; // ตัวเลขที่จะใส่ในเมทริกซ์ int[][] matrix = new int[rows][cols]; // สร้างเมทริกซ์ int direction = 0; // ทิศทางการเคลื่อนที่ (0-3) int x = 0, y = 0; // พิกัดปัจจุบัน int borderBottom = 0; // ตัวนับการชนขอบล่าง

2. การควบคุมทิศทาง

switch (direction % 4) { case 0: // ไปทางขวา (→) x++; if (x == cols - 1 && y == 0 || x == cols - 2 && y > 0) { direction = (y > 0) ? 3 : 1; } break; case 1: // ไปทางล่าง (↓) y++; if (y == rows - 1) direction++; break; case 2: // ไปทางซ้าย (←) x--; if (x == 0) direction = 3; break; case 3: // ไปทางบน (↑) y--; direction = (borderBottom % 2 == 0) ? 0 : 2; borderBottom++; break; }

หลักการสำคัญ

1. การเปลี่ยนทิศทาง

  • 0: เคลื่อนที่ไปทางขวา (→)
  • 1: เคลื่อนที่ไปทางล่าง (↓)
  • 2: เคลื่อนที่ไปทางซ้าย (←)
  • 3: เคลื่อนที่ไปทางบน (↑)

2. เงื่อนไขการเปลี่ยนทิศทาง

  • เมื่อชนขอบขวาบน: เปลี่ยนเป็นลง
  • เมื่อชนขอบล่าง: เปลี่ยนเป็นซ้าย
  • เมื่อชนขอบซ้าย: เปลี่ยนเป็นขึ้น
  • เมื่อขึ้นถึงบน: สลับระหว่างขวาและซ้าย

3. การจัดการพิเศษ

  • ใช้ borderBottom เพื่อติดตามการชนขอบล่าง
  • มีเงื่อนไขพิเศษสำหรับการเปลี่ยนทิศทางที่มุม

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

ปรับปรุงล่าสุด