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
广告