การสลับตำแหน่งของซับเมทริกซ์
โจทย์
A sub-matrix of a matrix is obtained by deleting any collection of rows and/or columns.
For example, from the following 3-by-4 matrix, we can construct a 2-by-3 sub-matrix by removing row 3 and column 2:
Transpose the sub-matrix by swapping rows and columns, as shown below.
Then print the transposed sub-matrix in a single line, matching the format in the output example.
Input:
- The first line of input specifies the number of rows and columns in the matrix.
- The second line specifies the row and column indices (starting from 0) to delete during sub-matrix transformation.
- The third line provides the matrix elements as a single list of numbers.
Output:
- The transposed sub-matrix in a single line.
| Input | Output |
|---|---|
| 3 4 2 1 1 2 3 4 5 6 7 8 9 10 11 12 | 1 5 3 7 4 8 |
โค้ด
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 delRow = scanner.nextInt();
int delCol = scanner.nextInt();
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int number = scanner.nextInt();
matrix[i][j] = (i == delRow || j == delCol) ? Integer.MIN_VALUE : number;
}
}
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
int number = matrix[i][j];
if (number == Integer.MIN_VALUE) continue;
System.out.print(number + " ");
}
}
}
}คำอธิบาย
1. การรับข้อมูล
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int delRow = scanner.nextInt();
int delCol = scanner.nextInt();- รับจำนวนแถว (
rows) และคอลัมน์ (cols) - รับตำแหน่งแถว (
delRow) และคอลัมน์ (delCol) ที่ต้องการลบ
2. การสร้างเมทริกซ์และทำเครื่องหมาย
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int number = scanner.nextInt();
matrix[i][j] = (i == delRow || j == delCol) ? Integer.MIN_VALUE : number;
}
}- สร้างเมทริกซ์ 2 มิติ
- รับค่าและทำเครื่องหมาย (
Integer.MIN_VALUE) ที่ตำแหน่งที่ต้องการลบ
3. การแสดงผลแบบ Transpose
for (int j = 0; j < cols; j++) {
for (int i = 0; i < rows; i++) {
int number = matrix[i][j];
if (number == Integer.MIN_VALUE) continue;
System.out.print(number + " ");
}
}- วนลูปคอลัมน์ก่อนแถว (เพื่อทำ transpose)
- ข้ามค่าที่ถูกทำเครื่องหมาย
- แสดงผลในบรรทัดเดียว
หลักการทำงาน
ตัวอย่างการทำงาน
กรณีตัวอย่างจากโจทย์
- สร้างเมทริกซ์เริ่มต้น:
1 2 3 4
5 6 7 8
9 10 11 12- ทำเครื่องหมายแถวที่ 2 และคอลัมน์ที่ 1 (X แทน MIN_VALUE):
1 X 3 4
5 X 7 8
X X X X- แสดงผลแบบ transpose (อ่านตามคอลัมน์ โดยข้าม X):
1 5 3 7 4 8ปรับปรุงล่าสุด