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

假如一个M x M 格子的盒子里有 n (n > 0)个新鲜橘子,有 m 个烂橘子。每隔一分钟我们去这个盒子里面数一数,直到烂橘子没有增加。结果就是:

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

};

}

每隔一分钟,一个放在 x 位置的格子的烂橘子,其他四个位置 x + 1、x - 1、x + M 、x - 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));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值