find neighbors in 2d array code example

Example: 2d array finding neighbors c++

#include <stdio.h>

#define ROWS 8
#define COLS 8

typedef int matrix_t[ROWS][COLS];

static int sum(matrix_t &matrix, int row, int col)
{
    int sum = 0;
    for (int i = -1; i < 2; i++)
    {
        for (int j = -1; j < 2; j++)
        {
            // skip center cell
            if (i == j) continue;
            // skip rows out of range.
            if ( (i + row) < 0 || (i + row >= ROWS) continue;
            // skip columns out of range.
            if ( (j + col) < 0 || (j + col >= COLS) continue;
            // add to sum.
            sum += matrix[i + row][j + col];
        }
    }
    return sum;
}

static int make(matrix_t &result, const matrix_t &source)
{
    for (int i = 0; i < ROWS; i++)
        for (int j = 0; j < COLS; j++)
            result[i][j] = sum(source, i, j);
}

// print a matrix to stdout.
static int print(const matrix_t &source)
{
    for (int i = 0; i < ROWS; i++)
    {
        for (int j = 0; j < COLS; j++)
            printf("\t%d", source[i][j]);
        printf("\n");
    }
}

// unit test
int main(int argc, char *argv[])
{
    matrix_t result = {0};
    const matrix_t source =
    {
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8}
    };
    make(result, source);
    puts("Source:");
    print(source);
    puts("Result:");
    print(result);
    return 0;
}
</stdio.h>

Tags:

Cpp Example