1.7 Matrix Traversal
চিনবেন কীভাবে
2D grid, "spiral", "rotate", walking along boundaries, layer by layer — simulate with direction/boundary variables
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন
Demo: Spiral Matrix — LC 54 (Medium)
Statement (Demo): Given an m × n integer matrix, return all its elements in spiral order (right → down → left → up).
Example: [[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5] | ⚡ m,n ≤ 10
Approach: Keep four boundaries (top/bottom/left/right). Walk one layer, then pull the boundaries in. Check the boundaries before the bottom and left passes, or a single inner row/column gets counted twice.
function spiralOrder(matrix) {
const res = [];
let top = 0,
bottom = matrix.length - 1;
let left = 0,
right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let j = left; j <= right; j++) res.push(matrix[top][j]);
top++;
for (let i = top; i <= bottom; i++) res.push(matrix[i][right]);
right--;
if (top <= bottom) {
for (let j = right; j >= left; j--) res.push(matrix[bottom][j]);
bottom--;
}
if (left <= right) {
for (let i = bottom; i >= top; i--) res.push(matrix[i][left]);
left++;
}
}
return res;
}
Complexity: Time O(m·n), Space O(1) (excluding output)
Demo · Spiral Matrixplan · দিন ০৪৬LC 54
নোট · ফাঁকা
প্রবলেম
- Rotate Imageplan · দিন ০৩০LC 48(transpose + reverse)
Statement: Given an
n × ninteger matrix, rotate it 90° clockwise in place. No extra matrix.
Example:[[1,2,3],[4,5,6],[7,8,9]]→[[7,4,1],[8,5,2],[9,6,3]]| ⚡n ≤ 20নোট · ফাঁকা
আরও দেখুন
BFS/DFS on a grid (islands, flood fill) → see 8.1