Search code examples
calgorithmmatrixborder

What is wrong with my 2-D array bordering algorithm?


I have a 2-D array in which I have to calculate the sum of the neighbours of each element, wrapping around margins and corners. So, if we had the matrix:

1 2 3
4 5 6
7 8 9,

computing the sum of the neighbours of the last element at position (2, 2):

neighSum(A[2][2]) = 8 + 5 + 6 + 4 + 7 + 1 + 3 + 2

The way I want to implement this is by adding outside borders to the matrix. There's no point in explaining because it would take a lot longer than a visual example, so building upon the previous one, the matrix becomes:

   7 8 9

3  1 2 3  1
6  4 5 6  4
9  7 8 9  7

   1 2 3

For the corners, there is a catch however. The matrix is considered to be a toroid, which is a geometric shape that has the form of a donut. Think of it as taking the original matrix, wrapping it around a vertical cylinder, and then wrapping it around a horizontal cylinder. This operation makes all the corners be neighbours and we just have to fill in what is left after adding borders.

9  7 8 9  7

3  1 2 3  1
6  4 5 6  4
9  7 8 9  7

3  1 2 3  1

So far I have come up with this algorithm, which pretty much works fine, except for the rightmost column, or so I think. It is behaving strangely, sometimes overwriting some of the values in the right border, sometimes the ones in the left border as well


/* Copy the original matrix to the bordered one */
for (i = 1; i < N + 1; i++)
{
    for (j = 1; j < M + 1; j++)
    {
        B[i][j] = A[i][j];
    }
}

/* Add the left and right borders */
for(i = 1; i < M + 1; i++)
{
    B[0][i] = B[N][i];
    B[N+1][i] = B[1][i];
}

/* Add the top and down borders */
for(j = 1; j < N+1; j++)
{
    B[i][0] = B[i][M];
    B[i][M+1] = B[i][1];
}

/* Mirror the corners */
B[0][0] = B[N][M];
B[M+1][N+1] = B[1][1];
B[N+1][0] = B[1][M];
B[0][M+1] = B[N][1];

Solution

  • Your last loop iterator is 'j' but you use 'i' to index elements.