Finding neighbours in a two-dimensional array

后端 未结 20 1193
忘了有多久
忘了有多久 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:36

    (pseudo-code)

    row_limit = count(array);
    if(row_limit > 0){
      column_limit = count(array[0]);
      for(x = max(0, i-1); x <= min(i+1, row_limit); x++){
        for(y = max(0, j-1); y <= min(j+1, column_limit); y++){
          if(x != i || y != j){
            print array[x][y];
          }
        }
      }
    }
    

    Of course, that takes almost as many lines as the original hard-coded solution, but with this one you can extend the "neighborhood" as much as you can (2-3 or more cells away)

提交回复
热议问题