Intermediate Level
Implement the spiralOrderTraversalLength method that returns the number of elements visited in spiral order.
The input contains a matrix with rows rows and cols columns.
Your task is to traverse the matrix in spiral order and return the number of elements visited during the traversal.
Spiral order starts from the top-left corner, moves right, then down, then left, then up, and continues inward until every cell has been visited.
Use four boundaries to control the traversal.
Maintain top, bottom, left, and right. Traverse the top row, then the right column, then the bottom row, then the left column. After each side is processed, move the boundary inward.
Increase the count whenever a cell is visited. Stop when the boundaries cross.
Pseudocode:
function spiralOrderTraversalLength(matrix, rows, cols):
top = 0
bottom = rows - 1
left = 0
right = cols - 1
count = 0
while top <= bottom AND left <= right:
for col from left to right:
count++
top++
for row from top to bottom:
count++
right--
if top <= bottom:
for col from right down to left:
count++
bottom--
if left <= right:
for row from bottom down to top:
count++
left++
return count