Finding neighbours in a two-dimensional array

后端 未结 20 1214
忘了有多久
忘了有多久 2020-11-30 02:02

Is there an easy way of finding the neighbours (that is, the eight elements around an element) of an element in a two-dimensional array? Short of just subtracting and adding

20条回答
  •  心在旅途
    2020-11-30 02:24

    I use a directions array and run a loop to get appropriate directions. Something like this (code is in JS)

    function getAdjacent(matrix, i, j, k) {
      const directions = [
        [i - 1, j - 1],
        [i - 1, j],
        [i - 1, j + 1],
        [i, j - 1],
        [i, j + 1],
        [i + 1, j - 1],
        [i + 1, j],
        [i + 1, j + 1],
      ];
      const [row, col] = directions[k];
      // Check for last rows and columns
      if (row < 0 || row >= matrix.length || col < 0 || col >= matrix[i].length) {
        return undefined;
      }
      return matrix[row][col];
    }
    
    function run(){
      const hello = 'hello';
      const matrix = [
        [1, 2, 1],
        [2, 1, 1],
        [1, 1, 1]
      ];
    
      for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < matrix[i].length; j++) {
          let sum = 0;
          for (let k = 0; k < 8; k++) {
            const res = getAdjacent(matrix, i, j, k);
            console.log(i, j, k, res); // Do whatever you want here
          }
        }
      }
    }
    
    run();

提交回复
热议问题