JavaScript二進位制矩陣中最近0的距離
二進位制矩陣是由陣列組成的陣列,其中僅包含 0 或 1。我們需要編寫一個 JavaScript 函式,該函式僅將二進位制矩陣作為唯一引數。
我們的函式應該建立一個包含相同行數和列數的新矩陣,並且對於原始矩陣的每個元素,所得矩陣應該包含該元素在原始矩陣中到 0 的最近距離。
我們必須牢記在計算距離時,它可以水平或垂直移動,而不能對角線移動。並且保證該矩陣至少包含一個 0。
例如 -
如果輸入矩陣為 -
const arr = [ [0, 0, 0] [0, 1, 0] [1, 1, 1] ];
那麼輸出矩陣應該是 -
const output = [ [0, 0, 0] [0, 1, 0] [1, 2, 1] ];
例項
程式碼如下 -
const arr = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 1],
];
const findNearestDistance = (arr = []) => {
let array = [];
let res = arr.map((el, ind) => el.map((subEl, subInd) => {
if (subEl === 0) {
array.push([ind, subInd])
return 0
};
return Number.MAX_SAFE_INTEGER;
}));
const updateAdjacent = (ind, subInd, min, array = []) => {
if (ind < 0 || subInd < 0 || ind == arr.length || subInd == arr[0].length){
return;
};
if (res[ind][subInd] < min + 2) return
res[ind][subInd] = min + 1
array.push([ind, subInd])
};
while (array.length) {
let next = []
for (let [ind, subInd] of array) {
updateAdjacent(ind, subInd + 1, res[ind][subInd], next)
updateAdjacent(ind, subInd - 1, res[ind][subInd], next)
updateAdjacent(ind + 1, subInd, res[ind][subInd], next)
updateAdjacent(ind - 1, subInd, res[ind][subInd], next)
};
array = next;
}
return res;
};
console.log(findNearestDistance(arr));輸出
控制檯中的輸出將是 -
[ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 1, 2, 1 ] ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP