Skip to content
Advertisement

How to check if 2 elements are adjacent to one another in 2D array

I’m trying to figure out how to take in 2 integer parameters, an initial integer referred to as “start” and a second integer referred to as “destination”. I’m wanting to use both parameters from my method, first checking if the starting integer is within the matrix and then checking if the destination integer is adjacent within the 4 elements around it – (north, east, south, west).

Example 1:

example1

If the starting integer is (6), check whether the destination integer (7) is adjacent to the starting integer. If true then do something.

Example 2:

example1

In this case if the starting integer = 4 and the destination integer = 2. The program would not consider these elements adjacent.

Initialising array:

JavaScript

Check method:

JavaScript

Bear in mind, the matrix won’t have duplicate numbers and will always stay the same.

How would I go about checking this?

I’ve spent a few hours looking at similar StackOverflow posts but I really can’t seem to grasp the examples given. Could someone guide me through it?

Advertisement

Answer

If your start element is in the matrix there are 4 possible spots to check for your destination element: LEFT, RIGHT, UP, DOWN. You could just add a variable which is set by default to false and check the 4 spots keeping in mind to don’t get out of bounds:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement