How to find the boundary elements of a matrix

Boundary elements of a matrix

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.

The colored elements are the boundary elements of the matrix

Algorithm

  1. Run two loops. One loop iterates along the rows, and the other iterates along the columns. During the iteration, execute the following steps:
    1. If the row number is either zero or the last rowthe number of rows = 1, print the element at the current position.
    2. If the column number is either zero or the last columnthe number of columns = 1, print the element at the current position.
  • Time complexity: O(N*N)
  • Space complexity: O(1)

Code

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);
}
}
Boundary elements of the matrix