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6 6 6 6 6 6 6 0 0 0 0 0 0 0 0
请帮我解决这个问题。谢谢!!!(java或javascript代码示例会很棒)
答案 0 :(得分:1)
首先,将1
的值更改为-1
,因为您需要使用1
作为标记。
然后,您可以迭代元素并执行检查,如果它具有标记-1
,则将其更改为实际值。继续使用右边和底部的元素。
如果找到了元素,则增加值。
function test(array, i, j, value) {
if (array[i] && array[i][j] === -1) {
array[i][j] = value;
test(array, i + 1, j, value);
test(array, i, j + 1, value);
return true;
}
}
var data = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1], [0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1], [0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]],
value = 1;
data.forEach(function (a) {
a.forEach(function (b, i, bb) {
bb[i] = -b;
});
});
data.forEach(function (a, i, aa) {
a.forEach(function (b, j, bb) {
test(aa, i, j, value) && value++;
});
});
document.getElementById('out').innerHTML = data.map(function (a) { return a.join(' '); }).join('\n');
<pre id="out"></pre>