Skip to content

Find neighbours in 2D grid

Posted on:June 6, 2022 at 04:06 AM

Finding neighbours in 2D grid.

This is note to myself on how to get different ways to get neighbours from current cell in a grid.

Lets suppose that we have following grid represented by 2D array.

const grid = [
  ["Top Left", "Top Center", "Top Right"],
  ["Middle Left", "Middle Center", "Middle Right"],
  ["Bottom Left", "Bottom Center", "Bottom Righ"],
];

We want to get all 4 neighbours (top, right, bottom and left) from a given position (row and col), so if our position is row=1,col=1 then all 4 neighbours would be [“Top Center”, “Middle Right”, “Bottom Center”, “Middle Left”]. In case we are on the border of the grid then we will return only valid neighbours so for example in case of row=0, col=0 our neighbours would be [“Top Center”, “Middle Left”]. Lets write code for this:

const getNeighbours = (grid, x, y) => {
  const results = [];
  const directions = [
    [-1, 0], // Left
    [0, 1], // Down
    [1, 0], // Right
    [0, -1], // Up
  ];
  for (const [dirX, dirY] of directions) {
    const newX = x + dirX;
    const newY = y + dirY;

    if (newX > -1 && newX < grid.length && newY > -1 && newY < grid[0].length) {
      // make sure grid has equal number of columns in rows
      results.push([newX, newY]);
    }
  }
  return results;
};
const grid = [
  ["Top Left", "Top Center", "Top Right"],
  ["Middle Left", "Middle Center", "Middle Right"],
  ["Bottom Left", "Bottom Center", "Bottom Righ"],
];
getNeighbours(grid, 1, 1).forEach(([row, col]) => console.log(grid[row][col]));
/*
  Top Center
  Middle Right
  Bottom Center
  Middle Left
*/

To get neighbours in all eight directions we can use the following directions array:

const directions = [  [-1, 0], // West
  [-1, 1], // Northwest
  [0, 1], // North
  [1, 1], // Northeast
  [1, 0], // East
  [1, -1], // Southeast
  [0, -1], // South
  [-1, -1], // Southwest
];

Lets take a look at another similar implementation in which we will use the following direction array: [0, 1, 0, -1, 0] the rest of the code remains the same here is what will change

const directions = [0, 1, 0, -1, 0];
for (let i = 0; i < directions.length - 1; i++) {
  const newX = x + directions[i];
  const newY = y + directions[i + 1];

  if (newX > -1 && newX < grid.length && newY > -1 && newY < grid[0].length) {
    // make sure grid has equal number of columns in rows
    results.push([newX, newY]);
  }
}

For eight directions you can use the following array: [0, 1, -1, 1, 1, 0, -1, -1, 0]

So these are the two most common ways to find neighbours in of a cell in grid.