时间限制:限制时间C/C++ 1秒,其他/Java 2s以内
内存限制:32768K
在一个地图中(地图由n*n个区域组成),有部分区域被感染病菌。感染区域每天都会把周围(上下左右)的4个区域感染。
请根据给定的地图计算,多少天以后,全部区域都会被感染。
如果初始地图上所有区域全部都被感染,或者没有被感染区域,返回-1
输入描述: 一行N*N个数字(只包含0,1,不会有其他数字)表示一个地图,数字间用,分割,0表示未感染区域,1表示已经感染区域 每N个数字表示地图中一行,输入数据共表示N行N列的区域地图。 例如输入1,0,1,0,0,0,1,0,1,表示地图 1,0,1 0,0,0,1,0,1
输出描述: 一个整数,表示经过多少天以后,全部区域都被感染
示例1
输入
1,0,1,0,0,0,1,0,1
输出
2
说明
1天以后,地图中仅剩余中心点未被感染;2天以后,全部被感染。
示例2
输入
0,0,0,0
输出
-1
说明
无感染区域
示例3
输入
1,1,1,1,1,1,1,1,1
输出
-1
说明
全部都感染
备注: 1<=N<200
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void async function () {
// Write your code here
while (line = await readline()) {
// 排除全零全一的情况
if (line.indexOf('0') < 0 || line.indexOf('1') < 0) {
console.log(-1)
return
}
// 提取二维数组
let list = line.split(',')
let len = Math.sqrt(list.length)
let arr = [],i = 0
while (i < list.length) {
let temp = []
for (let j = 0; j < len; j++){
temp.push(list[i])
i++
}
arr.push(temp)
}
let days = 0
// 计算感染天数
while (!isCheck(arr)) {
arr = infect(arr)
days++
}
console.log(days)
}
}()
// 判断是否全部感染
function isCheck(arr) {
for (let i = 0; i < arr.length; i++){
for (let j = 0; j < arr[i].length; j++){
if (arr[i][j] === '0') {
return false
}
}
}
return true
}
// 感染过程
function infect(arr) {
// 深拷贝一份新的二维数组作为单次感染的结果
let temp = JSON.parse(JSON.stringify(arr))
const k = temp.length
for (let i = 0; i < arr.length; i++){
for (let j = 0; j < arr[i].length; j++){
// 跳过非感染区
if (arr[i][j] === '0') continue;
// 若在范围内,就上下左右感染
if (i - 1 >= 0) {
temp[i - 1][j] = '1'
}
if (i + 1 < k) {
temp[i + 1][j] = '1'
}
if (j - 1 >= 0) {
temp[i][j - 1] = '1'
}
if (j + 1 < k) {
temp[i][j + 1] = '1'
}
}
}
return temp
}