ในบทความนี้ เราจะเรียนรู้วิธีการแสดงองค์ประกอบขอบ (Boundary Elements) ของเมทริกซ์ เมทริกซ์เป็นการนำเสนอองค์ประกอบในรูปแบบแถวและคอลัมน์ องค์ประกอบขอบคือองค์ประกอบที่ไม่ถูกล้อมรอบด้วยองค์ประกอบอื่นๆ ทั้ง 4 ทิศทาง เช่น องค์ประกอบในแถวแรก แถวสุดท้าย คอลัมน์แรก และคอลัมน์สุดท้าย
ตัวอย่างการทำงาน
สมมติข้อมูลนำเข้า (Input) คือ:
The input matrix: 9 8 9 8 8 7 8 7 7 6 7 6 6 5 6 5
ผลลัพธ์ที่ต้องการ (Output) คือ:
The border elements of the matrix is: 9 8 9 8 8 7 7 6 6 5 6 5
อัลกอริทึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศเมทริกซ์จำนวนเต็ม input_matrix และอ็อบเจกต์ของคลาส BoundaryElements ชื่อ border_values ขั้นตอนที่ 3 - กำหนดค่าให้กับเมทริกซ์ ขั้นตอนที่ 4 - วนลูปผ่านแต่ละองค์ประกอบด้วย for-loop 2 ชั้น ตรวจสอบว่าเป็นองค์ประกอบขอบหรือไม่ด้วยเงื่อนไข OR (x==0 || y==0 || x==length-1 || y==length-1) ขั้นตอนที่ 5 - แสดงองค์ประกอบขอบ ขั้นตอนที่ 6 - จบการทำงาน
ตัวอย่างที่ 1: เขียนโค้ดทั้งหมดในฟังก์ชัน main
public class BoundaryElements {
public static void main(String[] args) {
int input_matrix[][] = new int[][] {
{ 9, 8, 9, 8 },
{ 8, 7, 8, 7 },
{ 7, 6, 7, 6 },
{ 6, 5, 6, 5 }
};
System.out.println("The matrix is defined as: ");
for (int x = 0; x < input_matrix.length; x++) {
for (int y = 0; y < input_matrix[x].length; y++) {
System.out.print(input_matrix[x][y] + " ");
}
System.out.println();
}
BoundaryElements border_values = new BoundaryElements();
System.out.println("The border elements of the matrix is:");
for (int x = 0; x < input_matrix.length; x++) {
for (int y = 0; y < input_matrix[x].length; y++) {
if (x == 0 || y == 0 || x == input_matrix.length - 1
|| y == input_matrix[x].length - 1) {
System.out.print(input_matrix[x][y] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
ผลลัพธ์
The matrix is defined as: 9 8 9 8 8 7 8 7 7 6 7 6 6 5 6 5 The border elements of the matrix is: 9 8 9 8 8 7 7 6 6 5 6 5
ตัวอย่างที่ 2: ใช้ฟังก์ชันแยก (Object-Oriented Style)
public class BoundryElements {
public void Boundary_Elements(int input_matrix[][]) {
System.out.println("The matrix is defined as: ");
for (int x = 0; x < input_matrix.length; x++) {
for (int y = 0; y < input_matrix[x].length; y++) {
System.out.print(input_matrix[x][y] + " ");
}
System.out.println();
}
System.out.println("The border elements of the matrix is:");
for (int x = 0; x < input_matrix.length; x++) {
for (int y = 0; y < input_matrix[x].length; y++) {
if (x == 0 || y == 0 || x == input_matrix.length - 1
|| y == input_matrix[x].length - 1) {
System.out.print(input_matrix[x][y] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
int input_matrix[][] = new int[][] {
{ 9, 8, 9, 8 },
{ 8, 7, 8, 7 },
{ 7, 6, 7, 6 },
{ 6, 5, 6, 5 }
};
BoundryElements border_values = new BoundryElements();
border_values.Boundary_Elements(input_matrix);
}
}
ผลลัพธ์
The matrix is defined as: 9 8 9 8 8 7 8 7 7 6 7 6 6 5 6 5 The border elements of the matrix is: 9 8 9 8 8 7 7 6 6 5 6 5