Garrett Sitter
Garrett Sitter

Reputation: 349

How to determine if 2 elements are adjacent in a 2D array?

I’m trying to find the best way to determine if an element is adjacent to another element in an unsorted two-dimensional array. For example, if myArray[2,2] is passed to my comparison function, I want input equal to the elements at positions [1,2], [3,2], [2, 1], and [2,3] to return true, and any other input to return false. This is based on user input.

array example

For example, assume the target value "13" is stored at [2,2]. If the user inputs "8", the array is searched for the value "8", which is found at position [1, 2]. Since this is adjacent to the target value of [2,2], a true value is returned.

I’ve come up with a function to do this, but I can’t help but feel that I'm overlooking a more efficient/elegant way than the conditionals I’m currently using. I’m a novice with C so please excuse any mistakes.

Currently, I’m using the following function:

_Bool withinOneOf(int x1, int y1,  int x2, int y2)  //compare x,y of first array element to x,y of second array element
{   
    _Bool xtrue = 0, ytrue = 0;

    if(x1 == x2+1 || x1 == x2-1)
    {
        xtrue = 1;
    }

    if(y1 == y2+1 || y1 == y2-1)
    {
        ytrue = 1;
    }

    if(((x1==x2) && ytrue) || ((y1==y2) && xtrue))  //only want tiles that are adjacent vertically and horizontally, 
    {                                               //not diagonally.
        return 1;                        
    } 
    else 
    {                        
        return 0;                   
    }
}

Upvotes: 1

Views: 2094

Answers (1)

ecatmur
ecatmur

Reputation: 157314

It's less code to compute the distance under the Manhattan metric, and check whether that is equal to 1:

return (abs(x1 - x2) + abs(y1 - y2)) == 1;

Upvotes: 8

Related Questions