Given a matrix of size Row x Col Print the boundary elements of the matrix. Boundary elements are those elements which are not surrounded by elements on all four directions, i.e. elements in the first row, first column, last row and last column.
Example:
Input :
1 2 3
4 5 6
7 8 9
Output:
1 2 3
4 6
7 8 9
Approach:
- Take the matrix as input from the user of N × M dimension.
- Print the border elements of the matrix using for loop.
Below is the implementation of the problem statement:
Java
import java.util.*;
public class GFG {
public void Boundary_Elements( int mat[][])
{
System.out.println( "Input Matrix is : " );
for ( int i = 0 ; i < mat.length; i++) {
for ( int j = 0 ; j < mat[i].length; j++) {
System.out.print(mat[i][j]);
}
System.out.println();
}
System.out.println( "Resultant Matrix is :" );
for ( int i = 0 ; i < mat.length; i++) {
for ( int j = 0 ; j < mat[i].length; j++) {
if (i == 0 || j == 0 || i == mat.length - 1
|| j == mat[i].length - 1 ) {
System.out.print(mat[i][j]);
}
else {
System.out.print( " " );
}
}
System.out.println();
}
}
public static void main(String[] args)
{
int mat[][] = new int [][] { { 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 } };
GFG B_Values = new GFG();
B_Values.Boundary_Elements(mat);
}
}
|
Output
Input Matrix is :
123
456
789
Resultant Matrix is :
123
4 6
789
Time Complexity: O(N × M), where n and m are the dimensions of the matrix.
Space Complexity: O(N × M).
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
04 Jan, 2021
Like Article
Save Article