1
var containVirus = function (isInfected) {10
function findContaminated() {14
for (let i = 0; i < isInfected.length; i++) {15
for (let j = 0; j < isInfected[i].length; j++) {16
if (isInfected[i][j] === 1) {17
let key = `${i}-${j}`;18
if (key in visited) continue;19
else infected.push([i, j]);21
let zeroes = new Set();22
let perimeter = findPerimeter(i, j, visited, zeroes);24
// Find the largest potential infection perimeter based on the number of 0's neighboring infected cells25
if (!mostViral) mostViral = { i, j, perimeter, zeroes: zeroes.size };26
else if (zeroes.size > mostViral.zeroes)27
mostViral = { i, j, perimeter, zeroes: zeroes.size };32
walls += mostViral.perimeter;34
// Quarantine the most viral area35
quarantine(mostViral.i, mostViral.j);37
// Spread the infection throughout the remaining infected areas38
let alreadyInfected = {};39
for (let [row, col] of infected) {40
if (mostViral.i === row && mostViral.j === col) continue;41
else infect(row, col, alreadyInfected);48
while (findContaminated()) continue;51
function findPerimeter(row, col, visited, zeroes) {55
row >= isInfected.length ||56
col >= isInfected[0].length59
let key = `${row}-${col}`;61
// If the current cell is visited or quarantined, leave the perimeter unchanged62
if (visited[key] || isInfected[row][col] === -1) return 0;64
// If the current cell is not infected and not quarantined, increase the perimeter65
if (isInfected[row][col] === 0) {72
for (let [r, c] of directions) {73
perimeter += findPerimeter(row + r, col + c, visited, zeroes);78
function quarantine(row, col) {82
row >= isInfected.length ||83
col >= isInfected[0].length87
// Only quarantine infected cells and neighboring infected cells88
if (isInfected[row][col] === 1) isInfected[row][col] = -1;91
for (let [r, c] of directions) quarantine(row + r, col + c);94
function infect(row, col, alreadyInfected, neighbor = 0) {98
row >= isInfected.length ||99
col >= isInfected[0].length102
let key = `${row}-${col}`;104
// If the current cell is already infected or quarantined105
if (alreadyInfected[key] || isInfected[row][col] === -1) return;107
// If the current cell is clear but neighbors an infected cell, infect it108
if (isInfected[row][col] === 0 && neighbor === 1) {109
alreadyInfected[key] = true;110
return (isInfected[row][col] = 1);111
} else if (isInfected[row][col] === 1 && neighbor === 1) {112
alreadyInfected[key] = true;116
for (let [r, c] of directions)117
infect(row + r, col + c, alreadyInfected, neighbor + 1);