ในบทความนี้ เราจะเข้าใจวิธีการพิมพ์องค์ประกอบขอบเขตของเมทริกซ์ เมทริกซ์เป็นตัวแทนขององค์ประกอบในแถวและคอลัมน์ องค์ประกอบขอบเขตคือองค์ประกอบเหล่านั้นที่ไม่ได้ล้อมรอบด้วยองค์ประกอบทั้งสี่ทิศทาง ตัวอย่างเช่น องค์ประกอบในแถวแรก คอลัมน์แรก แถวสุดท้าย และคอลัมน์สุดท้าย
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
สมมติว่าข้อมูลที่เราป้อนคือ −
The input matrix: 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
อัลกอริทึม
Step 1 - START Step 2 - Declare an integer matrix namely input_matrix, an object of the class BoundaryElements namely border_values. Step 3 - Define the values. Step 4 - Iterate over each element of the matrix using two for-loops and check if the element is a boundary element using Boolean OR condition. Step 5 - Display the boundary elements. Step 5 - Stop
ตัวอย่างที่ 1
ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง
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
ในที่นี้ มีการกำหนดจำนวนเต็มก่อนหน้านี้ และเข้าถึงและแสดงค่าบนคอนโซล
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