Java程式列印矩陣的邊界元素
在本文中,我們將瞭解如何列印矩陣的邊界元素。矩陣是行和列中元素的表示形式。邊界元素是不被四個方向上的元素包圍的元素。例如,第一行、第一列、最後一行和最後一列中的元素。
以下是相同的演示 −
假設我們的輸入是 −
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP