殭屍末日案例研究 - JavaScript


一種惡性的殭屍病毒正在數字城市中蔓延。我們在數字疾病控制與預防中心工作,我們的工作是檢視城市地圖,並確定哪些區域受到殭屍病毒汙染,以便數字軍隊知道在哪裡投放炸彈。

它們是一種新型的數字殭屍,只能在垂直和水平方向移動,並且只能感染與自身相同的數字。

我們將得到一個包含數字的二維陣列。

由於某種神秘的原因,零號病人總是出現在城市的西北區域(矩陣的元素 [0][0]),並且瘟疫從那裡透過上下左右移動傳播到其他單元格。

我們必須建立一個函式,返回一個地圖(二維陣列),其中所有受汙染的區域標記為 1,未受病毒感染的區域標記為 0。

換句話說,我們必須找到所有與 [0][0] 值相同的矩陣元素,我們可以透過從 [0][0] 向下、向上、向右或向左移動到達這些元素 - 而不進入儲存任何其他值的欄位。

示例

以下是程式碼 -

const arr = [
   [9, 1, 2, 3, 4, 1, 2, 9],
   [9, 9, 9, 2, 1, 5, 9, 9],
   [9, 2, 9, 3, 7, 9, 1, 9],
   [6, 9, 9, 9, 0, 9, 2, 9],
   [5, 4, 3, 9, 9, 9, 4, 9],
   [9, 3, 9, 5, 8, 9, 9, 9],
   [9, 9, 9, 9, 9, 9, 7, 9],
   [9, 9, 1, 2, 3, 9, 8, 9]
];
const findZombies = arr => {
   let i, j, result = [],
   zombie = arr[0][0],
   tree = {};
   const chance = ([i, j]) => {
      if (!tree[i] || !tree[i][j]) return;
      result[i][j] = 1;
      var temp = tree[i][j];
      tree[i][j] = undefined;
      temp.forEach(chance);
   }
   for (i = 0; i < arr.length; i++) {
      result.push([]);
      for (j = 0; j < arr[i].length; j++) {
         result[i].push(0);
         if (arr[i][j] !== zombie) continue;
         if (!tree[i]) tree[i] = {};
         tree[i][j] = [[i, j - 1], [i, j + 1], [i - 1, j], [i + 1, j]].filter(([x, y]) => arr[x] && arr[x][y] === zombie);
      };
   };
   chance([0, 0]);
   return result;
};
console.log(findZombies(arr));

這將在控制檯上產生以下輸出 -

[
 [
   1, 0, 0, 0,
   0, 0, 0, 1
 ],
 [
   1, 1, 1, 0,
   0, 0, 1, 1
 ],
 [
   1, 0, 1, 0,
   0, 1, 0, 1
 ],
 [
   0, 1, 1, 1,
   0, 1, 0, 1
 ],
 [
   0, 0, 0, 1,
   1, 1, 0, 1
 ],
 [
   1, 0, 1, 0,
   0, 1, 1, 1
 ],
 [
   1, 1, 1, 1,
   1, 1, 0, 1
 ],
 [
   1, 1, 0, 0,
   0, 1, 0, 1
 ]
]

更新於: 2020年10月1日

181 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.