get “neighbours” directly next to value/node in 2d array/grid

Tags: ,



How would I change this method to not return the corner neighbours and instead only the neighbours directly above, below, left and right?

function getNeighbors(nodes, column, row) {
    var rowLimit = nodes.length - 1;
    var columnLimit = nodes[0].length - 1;

    for (let x = Math.max(0, column - 1); x <= Math.min(column + 1, columnLimit); x++) {
        for (let y = Math.max(0, row - 1); y <= Math.min(row + 1, rowLimit); y++) {
            if (x !== column || y !== row) {
                board.nodes[column][row].neighbours.push(nodes[x][y]);
            }
        }
    }
}

Answer

If you allow me, I would avoid those two for loops and I would just test directly, using ifs, to see if the neighbours I need exist.

See below, if my pseudo code helps you, I made an example 2D array filled with strings, but it is just for examplify the logic.

The example below is looking for the direct neighbours of nodes[2][1], which is in this case, “c1”, it has no bottom

let nodesExample = [
  ["a0", "a1", "a2"],
  ["b0", "b1", "b2"],
  ["c0", "c1", "c2"],
]

function getNeighbors(nodes, column, row) {
  let neighbours = []

  //top
  if (column > 0 && nodes[column - 1][row]) {
    neighbours.push("top: " + nodes[column - 1][row]);
  }

  //bottom
  if (column < nodes.length - 1 && nodes[column + 1][row]) {
    neighbours.push("bottom: " + nodes[column + 1][row]);
  }

  //left
  if (nodes[column][row - 1]) {
    neighbours.push("left: " + nodes[column][row - 1]);
  }

  //right
  if (nodes[column][row + 1]) {
    neighbours.push("right: " + nodes[column][row + 1]);
  }

  return neighbours
}

console.log(getNeighbors(nodesExample, 2, 1))


Source: stackoverflow