Matrix: Given a matrix, print the boundary elements

Problem Statement:

You are given a matrix mat[m][n].
You need to print the boundary elements in clockwise, starting from top left element.

Example:

Input:  

m[] [] = { {1, 2, 3},
		   {4, 5, 6},
		   {6, 7, 8} };

Output : 1, 2, 3, 5, 8, 7, 6, 4

Solution Explanation:

Solution is very simple. We perform boundary traversal of the elements and print the elements.

Time Complexity: O(m + n)
Space Complexity: O(m + n)

Code Solution

#include <iostream>
#include <vector>
using namespace std;

vector<int> solution(vector<vector<int> >& mat) {
	
	int n = mat.size();
	int m = mat[0].size();
	
	vector<int> res;
	
	// left to right
	for (int j=0; j<m; j++) {
		res.push_back(mat[0][j]);
	}
    
    //last column
	for (int i=1; i<n; i++) {
		res.push_back(mat[i][m-1]);
	}
    
    // bottom row
	for (int j=m-2; j>=0; j--) {
		res.push_back(mat[n-1][j]);
	}
    
	for (int i=n-2; i>0; i--) {
		res.push_back(mat[i][0]);
	}

	return res;
}

int main() {
    
	vector<vector<int>> m = {
	    {1, 2, 3},
	    {4, 5, 6},
	    {6, 7, 8}
	};
	
	vector<int> res = solution(m);
	for (auto val: res) {
	    cout << val << " ";
	}
	cout << endl;

	return 0;
}

Output

1 2 3 6 8 7 6 4
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *