# 答案——腐烂的橘子算法题目

1.并且还有新鲜的橘子，返回 -1。

2.没有新鲜的橘子，返回分钟数。

``````function initData(a){
var
result = [],
n = 0,
m = 0,
j = 0;
for(j = 0; j < M; j++) {
result[j * M + 0] = { status: a[j][0], willBletOthers: a[j][0] === 2 };
result[j * M + 1] = { status: a[j][1], willBletOthers: a[j][1] === 2 };
result[j * M + 2] = { status: a[j][2], willBletOthers: a[j][2] === 2 };

if (a[j][0] == 1) {
n += 1;
}
if (a[j][1] == 1) {
n += 1;
}
if (a[j][2] == 1) {
n += 1;
}

if (a[j][0] == 2) {
m += 1;
}
if (a[j][1] == 2) {
m += 1;
}
if (a[j][2] == 2) {
m += 1;
}
}
return {
result: result,
n: n,
m: m
};
}

``````

``````function blet(index, result){
var bletNum = 0;
if(-1< index + 1 && index + 1 < M*M && result[index + 1].status == 1){
bletNum += 1;
result[index + 1] = {status: 2, willBletOthers: false}
}
if(-1< index + M && index + M < M*M && result[index + M].status == 1){
bletNum += 1;
result[index + M] = {status: 2, willBletOthers: false}
}

if(-1< index - 1 && index - 1 < M*M && result[index - 1].status == 1){
bletNum += 1;
result[index - 1] = {status: 2, willBletOthers: true}
}
if(-1< index - M && index - M < M*M && result[index - M].status == 1){
bletNum += 1;
result[index - M] = {status: 2, willBletOthers: true}
}
return bletNum;
}
var
M = 3,
rawData = [[2, 1, 1], [1, 1, 0], [0, 1, 1]];

function letGo(rawData){
var data = initData(rawData),
result = data.result,
n = data.n,
m = data.m,
k,
mins = 0,
sum;

if(m == 0 && n > 0){
return -1;
}
if(m == 0 && n == 0){
return 0;
}
while (n > 0 && m > 0) {
mins += 1;
sum = 0;
for (k = 0; k < result.length; k++) {
if (result[k].status == 2) {
if (result[k].willBletOthers) {
sum += blet(k, result);
} else {
result[k].willBletOthers = true;
}
}
}

if (sum === 0) {
break;
} else {
n -= sum;
m += sum;
}
}

return mins;
}

console.log(letGo(rowData));

``````

1.1k 声望
14 粉丝
0 条评论