所以我有一个输入2D数组,其中已经放置了地雷:
const input = [
[0, 0, '*'],
['*', 0, 0],
[0, '*', 0]
];
我需要做的是将更改后的2D数组输出并向邻居添加数字,但是我不知道如何优雅地访问它们。
const mineSweeper = (input) => {
for (let row = 0; row < input.length; row++) {
for (let col = 0; col < input[row].length; col++) {
if (input[row][col] === '*') {
// How can I access neighbors from here elegantly?
}
}
}
}
输出应如下所示:
const output = [
[1, 2, '*'],
['*', 3, 2],
[2, '*', 1]
];
任何提示?谢谢。
const dx = [1, 1, 1, 0, 0, -1, -1, -1];
const dy = [1, 0, -1, 1, -1, 1, 0, -1];
const mineSweeper = (input) => {
for (let row = 0; row < input.length; row++) {
for (let col = 0; col < input[row].length; col++) {
if (input[row][col] === '*') {
for (let i = 0 ; i < 8 ; i++) {
let nr = row + dy[i], nc = col + dx[i];
//check that is within the limits
if (nr >= 0 && nr < input.length && nc >= 0 && nc < input[row].length) {
input[nr][nc] = //Do what you need with this neighbor
}
}
}
}
}
}
不是最优雅的解决方案
const input = [
[0, 0, '*'],
['*', 0, 0],
[0, '*', 0],
];
const mineSweeper = input => {
for (let row = 0; row < input.length; row++) {
for (let col = 0; col < input[row].length; col++) {
if (input[row][col] === '*') {
Number.isInteger(input[row - 1] && input[row - 1][col]) && input[row - 1][col]++;
Number.isInteger(input[row] && input[row][col - 1]) && input[row][col - 1]++;
Number.isInteger(input[row + 1] && input[row + 1][col]) && input[row + 1][col]++;
Number.isInteger(input[row] && input[row][col + 1]) && input[row][col + 1]++;
Number.isInteger(input[row - 1] && input[row - 1][col - 1]) && input[row - 1][col - 1]++;
Number.isInteger(input[row + 1] && input[row + 1][col + 1]) && input[row + 1][col + 1]++;
Number.isInteger(input[row - 1] && input[row - 1][col + 1]) && input[row - 1][col + 1]++;
Number.isInteger(input[row + 1] && input[row + 1][col - 1]) && input[row + 1][col - 1]++;
}
}
}
};
mineSweeper(input);
console.log(input);
您可以使用双嵌套map
来获取每个元素,然后可以创建另一个函数,该函数将获取行和列的当前索引并检查每个元素的关闭*
。
const input = [
[0, 0, '*'],
['*', 0, 0],
[0, '*', 0]
]
function count(data, i, j) {
let c = 0;
const prevRow = data[i - 1];
const currentRow = data[i]
const nextRow = data[i + 1];
[prevRow, currentRow, nextRow].forEach(row => {
if (row) {
if (row[j - 1] == '*') c++;
if (row[j] == '*') c++;
if (row[j + 1] == '*') c++;
}
})
return c;
}
function update(data) {
return input.map((a, i) => {
return a.map((b, j) => {
return b == '*' ? b : count(data, i, j)
})
})
}
const result = update(input)
console.log(result)