1.7 Matrix Traversal
চিনবেন কীভাবে
2D grid, "spiral", "rotate", boundary ধরে ধরে হাঁটা, layer-by-layer — direction/boundary ভেরিয়েবল দিয়ে simulation
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন
Demo: Spiral Matrix — LC 54 (Medium)
Statement (Demo): m × n integer matrix দেওয়া — spiral order-এ (ডান → নিচ → বাম → উপর) সব element-এর list return করুন।
উদাহরণ: [[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5] | ⚡ m,n ≤ 10
Approach: চারটা boundary (top/bottom/left/right) রাখুন। এক layer ঘুরে boundary গুটিয়ে আনুন। ভেতরের দিকের single row/column-এ ডাবল-কাউন্ট এড়াতে নিচ ও বাম পাসের আগে boundary চেক জরুরি।
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) (output বাদে)
প্রবলেম
- Rotate Imageplan · দিন ০৪০LC 48(transpose + reverse)
Statement:
n × n2D integer matrix দেওয়া — এটাকে in-place clockwise 90° ঘুরান। Extra matrix ব্যবহার করা যাবে না।
উদাহরণ:[[1,2,3],[4,5,6],[7,8,9]]→[[7,4,1],[8,5,2],[9,6,3]]| ⚡n ≤ 20নোট · ফাঁকা
আরও দেখুন
Grid-এ BFS/DFS (islands, flood fill) → দেখুন 8.1