jeudi 24 mars 2016

Neighbors in an array

I'm having trouble figuring out how to identify the 1's in the array listed in my code below while taking into account the corners & edges of the array.

#include <stdio.h>
/* define grid size */
#define SIZE 7
int grid[SIZE][SIZE];
/* function to find the number of occupied adjacent cells */
int neighbors (int i, int j);
void main ()
{
  int i, j, n;
/* initialize the entire grid to be zero */
 for (i = 0; i < SIZE; i++)
    for (j = 0; j < SIZE; j++)
        grid[i][j] = 0;
/* introduce a few ones */
    grid[1][2] = 1;
    grid[2][2] = 1;
    grid[1][4] = 1;
    grid[2][4] = 1;
    grid[3][2] = 1;
    grid[3][3] = 1;
    grid[3][4] = 1;
    grid[5][3] = 1;
    grid[6][2] = 1;
for (i = 0; i < SIZE; i++)
   for (j = 0; j < SIZE; j++) {
      n = neighbors(i,j);
      printf ("Number of neighbors to element %d,%d =%d\n",i,j,n);
}
 return;
}
/* function to compute the neighbors */
int neighbors (int i, int j)

I figure that I can use if statements to alter how the code will run if i=0 or i=6, as well as if j=0 or j=6, but I'm not sure how to proceed. Any help would be much appreciated

Aucun commentaire:

Enregistrer un commentaire