
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print All Non-Boundary Elements of Matrix in C++
A matrix is a two-dimensional array. The elements that are present on the edges are called boundary elements, and the elements that are present inside the matrix, not present on the edges, are known as non-boundary elements. In this article, we are going to discuss how to print non-boundary elements of the matrix.
Problem Description
We are given a matrix and we have to print all non-boundary elements present in the matrix. Rows and columns are present in the matrix. The horizontal lines are called rows and the vertical lines are called columns. Below are some examples to understand the problem clearly:
Example 1
Input
1 2 3 4 5 6 7 8 9
Output
5
Example 2
Input
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Output
8 9 10 11 14 15 16 17 20 21 22 23 26 27 28 29
Approach
The approach involves the following steps:
- Check if the matrix has only one row or one column. If true, then there are no boundary elements in the matrix.
- Identify the boundary elements:
For rows, the boundary elements are present in the first row (row 0) or the last row (row = rows - 1).
For columns, the boundary elements are present in the first column (column 0) or the last column (column = columns - 1). - Traverse the matrix and print only the non-boundary elements, skipping the identified boundary elements.
C++ program to print all non-boundary elements of matrix
#include <bits/stdc++.h> using namespace std; void nonBoundaryElements(int rows, int cols, int matrix[5][6]) { // Check edge case if (rows < 3 || cols < 3) { cout << "No non-boundary elements exist in the matrix." << endl; return; } // Skip row elements for (int i = 1; i < rows - 1; i++) { // Skip column elements for (int j = 1; j < cols - 1; j++) { cout << matrix[i][j] << " "; } cout << endl; } } int main() { int rows = 5, cols = 6; int matrix[5][6] = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}, {19, 20, 21, 22, 23, 24}, {25, 26, 27, 28, 29, 30} }; // Print the non-boundary elements cout << "Non-boundary elements of the matrix are:" << endl; nonBoundaryElements(rows, cols, matrix); return 0; }
Output
Non-boundary elements of the matrix are: 8 9 10 11 14 15 16 17 20 21 22 23
Time and Space Complexities
Time Complexity: O(rows à columns), as we are traversing the rows and columns except the boundary elements.
Space Complexity: O(1), as we are not using any data structure.