![]() |
VOOZH | about |
In this article, we are going to learn how to print only the boundary elements of a given matrix in Java. Boundary elements mean the elements from the first row, last row, first column, and last column.
Example:
Input :
1 2 3
4 5 6
7 8 9Output:
1 2 3
4 6
7 8 9
Now, let's understand the approach we are going to use in order to solve this problem.
Approach:
Let's now see the real implementation of this for better understanding
Example: Here, we are printing the boundary elements of a matrix.
Input Matrix is: 1 2 3 4 5 6 7 8 9 Resultant Matrix is: 1 2 3 4 6 7 8 9
Explanation: Here, the outer loop is traversing the matrix row wise and column wise and the condition inside the inner loop checks whether the current element lies on the boundary or not. If it lies on the boundary the element is printed otherwise the space will be printed and this way we can only print the boundary elements.
Time Complexity: The time complexity is O(N × M)
Space Complexity: The space complexity is O(1)
Note: Here, n and m are the dimensions of the matrix.