1 回答
TA贡献2019条经验 获得超9个赞
如果您没有起始坐标,识别每个要填充的 0 的一种方法是识别边缘上的每个 0。这些零中的每一个都不应该被填充,并且最终与这些0相邻的每个0也不应该被填充。因此,如果您将边缘 0 作为“起点”并遍历它们的所有递归邻居,您将识别出每个坐标为 0 但不应填充。
然后,它很简单:只需遍历输入,对于每个 0,检查当前坐标是否在不应填充的那组坐标中。如果坐标不在该集合中,则替换为 2。
var map =
[[0,1,1,0,0,0,0,0,0,0],
[0,1,2,1,0,1,1,0,0,0],
[0,1,2,2,1,2,2,1,0,0],
[0,1,2,2,2,2,2,2,1,0],
[0,0,1,2,2,2,2,1,0,0],
[0,0,0,1,2,2,2,1,1,0],
[0,0,1,2,2,2,1,0,0,0],
[0,1,2,2,2,2,2,1,0,0],
[1,2,2,1,1,1,2,1,0,0],
[0,1,1,0,0,1,1,1,0,0]];
const height = map.length;
const width = map[0].length;
const edgeZerosCoords = new Set();
map.forEach((arr, row) => {
arr.forEach((num, col) => {
if (num === 0 && (row === 0 || col === 0 || row === width - 1 || col === height - 1)) {
edgeZerosCoords.add(`${row}_${col}`);
}
})
});
const doNotFillCoords = new Set();
const visited = new Set();
const checkCoord = (row, col) => {
// Verify valid coord:
if (row < 0 || col < 0 || row === width || col === height) return;
const str = `${row}_${col}`;
if (doNotFillCoords.has(str) || visited.has(str)) return;
visited.add(str);
const num = map[row][col];
if (num !== 0) return;
doNotFillCoords.add(str);
checkCoord(row + 1, col);
checkCoord(row - 1, col);
checkCoord(row, col + 1);
checkCoord(row, col - 1);
};
for (const str of edgeZerosCoords) {
const [row, col] = str.split('_').map(Number);
checkCoord(row, col)
}
map.forEach((arr, row) => {
arr.forEach((num, col) => {
const str = `${row}_${col}`;
if (num === 0 && !doNotFillCoords.has(str)) {
map[row][col] = 2;
}
})
});
console.log(JSON.stringify(map));
结果:
[
[0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 2, 1, 0, 1, 1, 0, 0, 0],
[0, 1, 2, 2, 1, 2, 2, 1, 0, 0],
[0, 1, 2, 2, 2, 2, 2, 2, 1, 0],
[0, 0, 1, 2, 2, 2, 2, 1, 0, 0],
[0, 0, 0, 1, 2, 2, 2, 1, 1, 0],
[0, 0, 1, 2, 2, 2, 1, 0, 0, 0],
[0, 1, 2, 2, 2, 2, 2, 1, 0, 0],
[1, 2, 2, 1, 1, 1, 2, 1, 0, 0],
[0, 1, 1, 0, 0, 1, 1, 1, 0, 0]
]
添加回答
举报