[英]How to find the diagonals of a point in a 2D Array
我有一個像這樣的二維數組:
const matrix = [
[0, 0, 0, 0],
[0, 2, 1, 0],
[0, 1, 2, 0],
[0, 0, 0, 0]
]
如果給定單元格的x
和y
,例如2
和1
( matrix[2][1]
為1
),我如何找到所有對角線(兩條 arrays,每條都包含以正確順序對角線)通過提供的單元格? 矩陣(數組)總是對稱的和正方形的(准確地說,我有一個 8x8 的網格)。
例子:
const matrix = [
[0, 0, 0, 0],
[0, 2, 1, 0],
[0, 1, 2, 0],
[0, 0, 0, 0]
];
const cellX = 2, cellY = 1;
// Code ...
const diagonalFromTopLeft = [0, 1, 0];
const diagonalFromTopRight = [0, 1, 1, 0]
如果您能夠找到每條線,而不僅僅是對角線(垂直和水平,但我自己可以弄清楚),則可以加分。
您可以迭代行(和相應的索引)並計算兩條對角線上的相應 x 坐標。 當它們在范圍內時,可以將相應的值添加到相關數組中:
function diagonals(matrix, cellX, cellY) { let forward = []; // diagonal according forward slash shape: / let backward = []; // diagonal according backslash shape: \ let n = matrix.length; matrix.forEach((row, y) => { let x = cellX - (cellY - y); if (x >= 0 && x < n) backward.push(row[x]); x = cellX + (cellY - y); if (x >= 0 && x < n) forward.push(row[x]); }); return [forward, backward]; } const matrix = [ [0, 0, 0, 0], [0, 2, 1, 0], [0, 1, 2, 0], [0, 0, 0, 0] ]; const cellX = 2, cellY = 1; console.log(diagonals(matrix, cellX, cellY));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.