The boundary elements of a matrix are found at the boundary of the matrix.
For example, consider the matrix below.
[1, 2, 3, 4]
[4, 5, 6, 5]
[7, 8, 9, 6]
The boundary elements of the matrix are as follows.
1 2 3 4
4 5
7 8 9 6
The following image offers a visual representation for clarity.
O(N*N)
O(1)
The code below finds the boundary elements of a matrix and displays the boundary element in output.
import java.util.Arrays;public class Main{private static void printBoundaryElements(int[][] matrix){// get the number of rows in the matrixint numRows = matrix.length;// get the number of columns in the matrixint numCols = matrix[0].length;// Loop through every row in the matrixfor(int i = 0; i < numRows; i++){// Loop through every column in the matrixfor(int j = 0; j < numCols; j++){// check whether the condition for boundary element is trueif (i == 0 || j == 0 || i == numRows - 1 || j == numCols - 1)System.out.print(matrix[i][j] + " ");elseSystem.out.print(" ");}System.out.println();}}private static void printMatrix(int[][] matrix){for (int[] row : matrix)System.out.println(Arrays.toString(row));}public static void main(String[] args){int matrix[][] = {{1, 2, 3, 4},{4, 5, 6, 5},{7, 8 , 9, 6}};printMatrix(matrix);System.out.println("The boundary elements of the above matrix is as follows:");printBoundaryElements(matrix);}}