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 matrix int numRows = matrix.length; // get the number of columns in the matrix int numCols = matrix[0].length; // Loop through every row in the matrix for(int i = 0; i < numRows; i++) { // Loop through every column in the matrix for(int j = 0; j < numCols; j++) { // check whether the condition for boundary element is true if (i == 0 || j == 0 || i == numRows - 1 || j == numCols - 1) System.out.print(matrix[i][j] + " "); else System.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); } }
RELATED TAGS
CONTRIBUTOR
View all Courses