Take matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]. Start with top=0, bottom=2, left=0, right=3.
Right along row : collect . Set top=1. Down along column : collect . Set right=2. Left along row : collect . Set bottom=1. Up along column : collect . Set left=1.
Now top=1, bottom=1, left=1, right=2. Right along row : collect . Set top=2. Now top > bottom, so you stop. Result: [1,2,3,4,8,12,11,10,9,5,6,7].
Time: . You visit each cell exactly once. Space: excluding the output array. You only track the boundary variables.