提问者:小点点

JavaScript:2D Array Minesweeper访问邻居+=1他们


所以我有一个输入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]
];

有小费吗? 谢了。


共3个答案

匿名用户

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
           }
        }
      }
    }
  }
}

匿名用户

您可以使用双重嵌套的map获取每个元素,然后创建另一个函数,该函数将获取行和列的当前索引,并检查每个元素的关闭*

null

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)

匿名用户

您可以获得一个偏移量数组来获得正确的索引,并检查该值是否为星型。

null

const
    getCount = (array, x, y) => offsets
        .reduce((c, [i, j]) => c + (array[x + i]?.[y + j] === '*'), 0),
    offsets = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]],
    input = [[0, 0, '*'], ['*', 0, 0], [0, '*', 0]],
    result = input.map((row, i, a) => row.map((v, j) => v || getCount(a, i, j)));

result.forEach(a => console.log(a.join(' ')));