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
out
to store the boundary elements.Initialize variables
i
andj
to track the current position in the matrix, both starting at 0.Traverse the top row from left to right, incrementing
j
while adding elements toout
.Increment
i
and decrementj
to 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
i
and adding elements toout
.If there are more than one rows, return to the first column by incrementing
j
and traverse the bottom row from bottom to top while decrementingi
and adding elements toout
.Return the
out
vector as the result.
Time and Auxiliary Space Complexity
Time Complexity: The time complexity of this solution is
O(N + M)
, whereN
is the number of rows in the matrix andM
is 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++)
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