Print the matrix in spiral manner
MediumFour moving boundaries closing inwards
Problem
Given an M * N matrix, print the elements in a clockwise spiral manner. Return an array with the elements in the order of their appearance when printed in a spiral manner.
Walk right, down, left, up, shrinking the boundary after each side.
The idea
Hold top, bottom, left and right boundaries and walk one edge at a time, shrinking the relevant boundary after each edge. Re-checking that the boundaries have not crossed before the bottom and left edges is what stops a single remaining row or column being printed twice.
The trick
- Order: left-to-right along top, down the right, right-to-left along bottom, up the left.
- Check top <= bottom and left <= right again before the last two edges.
- O(rows x cols), each cell printed once.
Step 1 of 18. Peel the matrix in rings: go right along the top, down the right, left along the bottom, up the left.
Peel the matrix ring by ring.
1while (top <= bottom && left <= right) {2 for (let c=left; c<=right; c++) out.push(M[top][c]); top++;3 for (let r=top; r<=bottom; r++) out.push(M[r][right]); right--;4 if (top<=bottom) for (let c=right;c>=left;c--) out.push(M[bottom][c]); bottom--;5 if (left<=right) for (let r=bottom;r>=top;r--) out.push(M[r][left]); left++;6}Input
- grid
- 4 × 4
Memory
- at
- —
- cells marked
- 0
Output
- output
- —
- done
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- matrix = [[1,2,3],[4,5,6],[7,8,9]]
- Output:
- [1, 2, 3, 6, 9, 8, 7, 4, 5]
- Explanation:
- Peel the outer ring, then spiral inward.
Example 2
- Input:
- matrix = [[1,2],[3,4]]
- Output:
- [1, 2, 4, 3]
- Explanation:
- 1,2,4,3 winds around.
Example 3
- Input:
- matrix = [[1]]
- Output:
- [1]
- Explanation:
- A single cell.
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 100
- -100 <= matrix[i][j] <= 100
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.