Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get adjacent elements in a two-dimensional array?

I have a two-dimensional array, say

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

And i need to get all the numbers adjacent to 1(2, 3, 4, 5, 6, 7, 8, 9)

Is there a less ugly solution than:

topLeft = array[x-1][y-1] top  = array[x][y-1] topRight = array[x+1][y-1] # etc 

Thanks!

like image 373
Ian P Avatar asked Jan 10 '10 00:01

Ian P


People also ask

What are adjacent elements in 2D array?

Adjacent elements are all the elements that share a common side or point i.e., they have a vertical, horizontal or diagonal distance of 1.

How do you find the elements of a 2D array?

An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array. int x = a[1,1]; Console.

What is adjacent elements in matrix?

The adjacent elements of the matrix can be top, down, left, right, diagonal, or anti-diagonal. The four or more numbers should be adjacent to each other. Note: n should be greater than or equal to 4 i.e n >= 4.


1 Answers

If you're not worried about the order, the cleanest is probably to use a couple of loops:

result = new List<int>(8); for (dx = -1; dx <= 1; ++dx) {     for (dy = -1; dy <= 1; ++dy) {         if (dx != 0 || dy != 0) {             result.Add(array[x + dx][y + dy]);         }     } } 

If the order is important, you can construct a list of all the (dx, dy) in the order you want and iterate over that instead.

As pointed out in the comments, you probably want to add boundary checks. You could do that like this (assuming order doesn't matter):

List<int> result = new List<int>(8); for (int dx = (x > 0 ? -1 : 0); dx <= (x < max_x ? 1 : 0); ++dx) {     for (int dy = (y > 0 ? -1 : 0); dy <= (y < max_y ? 1 : 0); ++dy)     {         if (dx != 0 || dy != 0)         {             result.Add(array[x + dx][y + dy]);         }     } } 
like image 61
Mark Byers Avatar answered Oct 27 '22 13:10

Mark Byers