1. Boundary Traversal of Matrix
The problem of boundary traversal of a matrix can be found at the following link: Question Link
Approach
To perform the boundary traversal of a matrix, I followed these steps:
Initialize an empty vector
outto store the boundary elements.Initialize variables
iandjto track the current position in the matrix, both starting at 0.Traverse the top row from left to right, incrementing
jwhile adding elements toout.Increment
iand decrementjto position at the last column if there is more than one row.If there are more than one rows and more than one columns, traverse the rightmost column from top to bottom while decrementing
iand adding elements toout.If there are more than one rows, return to the first column by incrementing
jand traverse the bottom row from bottom to top while decrementingiand adding elements toout.Return the
outvector as the result.
Time and Auxiliary Space Complexity
Time Complexity: The time complexity of this solution is
O(N + M), whereNis the number of rows in the matrix andMis the number of columns in the matrix. We visit each element of the matrix once.Auxiliary Space Complexity: The auxiliary space complexity is
O(N+M)because we only use a single vector to store the result.
Code (C++)
class Solution {
public:
vector<int> boundaryTraversal(vector<vector<int>>& matrix, int n, int m) {
vector<int> out;
int i = 0, j = 0;
for(; j < m; ++j) out.push_back(matrix[i][j]);
++i; --j;
if(n > 1) {
for(; i < n; ++i) out.push_back(matrix[i][j]);
--i; --j;
if(m > 1) {
for(; j >= 0; --j) out.push_back(matrix[i][j]);
--i; ++j;
for(; i > 0; --i) out.push_back(matrix[i][j]);
}
}
return out;
}
};Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated
Was this helpful?