Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิ่งเฉียง (Diagonal Traversal) ในเมทริกซ์สี่เหลี่ยมจัตุรัสด้วย JavaScript

ปัญหา

รับเมทริกซ์สี่เหลี่ยมจัตุรัส วิ่งเฉียง (zigzag diagonal) เก็บค่าในอาร์เรย์ตามลำดับที่เจอ

ตัวอย่าง

const arr = [[1,2,3],[4,5,6],[7,8,9]];

ลำดับ: 1, 2, 4, 7, 5, 3, 6, 8, 9 → [1,2,4,7,5,3,6,8,9]

โค้ดตัวอย่าง

const arr = [[1,2,3],[4,5,6],[7,8,9]]; 
const findDiagonalOrder = (arr = []) => { 
  if(!arr.length) return []; 
  let ind = 0, colBegin = 0, rowBegin = 0; 
  let rowMax = arr.length, colMax = arr[0].length; 
  const res = [], stack = []; 
  while(rowBegin < rowMax || colBegin < colMax) { 
    for(let row = rowBegin, col = colBegin; row < rowMax && col >=0; row++, col--){ 
      if(ind % 2 === 0){ stack.push(arr[row][col]); } 
      else { res.push(arr[row][col]); } 
    } 
    ind++; 
    while(stack.length){ res.push(stack.pop()); } 
    colBegin++; 
    if(colBegin > colMax-1 && rowBegin < rowMax){ colBegin = colMax-1; rowBegin++; } 
  } 
  return res; 
}; 
console.log(findDiagonalOrder(arr));

คำอธิบาย

  • วิ่งแนวทแยง สลับทิศทางด้วย stack
  • ติดตามจุดเริ่มต้นแถว/คอลัมน์

ผลลัพธ์

[1, 2, 4, 7, 5, 3, 6, 8, 9]