Complexity of Spiral Traversal
The algorithm that traverses the matrix in spiral order visits each item of the matrix exactly once. As the matrix has m * n
entries, hence the time complexity is O(m * n)
.
We are using a fixed number of variables to solve the problem, and hence the space complexity is O(1)
.
Concluding Remarks
In this tutorial we have described a simple and easy to understand method for traversing any m * n
matrix in spiral order. The algorithm has linear time complexity in terms of the total entries of the matrix. When you implement your own routine for this traversal, your main challenge would be to make sure you don't exceed the bounds of the matrix and do not traverse any element more than once.