In: Computer Science
how to find all the neighbors in a n-dimensional array
in python?
thank you in advance
all the neighboors of a coordinate*
We can do that recursively easily.
We can use the concept of Cartesian Product here to do that .
Try to understand and visualize the n-dimensional array , we are currently on some cordinate * we want all the co-ordinates in range (-1 to 1) calculating from current co-ordinate
So for example in 2-D matrix if we are on co-ordinate (x,y) we can say the neighbors are (x-1,y) , (x-1,y-1) ,(x-1,y+1) , (x,y-1) ,(x,y+1) , (x+1,y+1) ,(x+1,y) , (x+1,y-1)
As it is for 2-D matrix we can easily get the neighbors all we have done is consider all cases where the difference between the co-ordinates is in between range -1 to 1 . ( Just the reference co-ordinate is to be ignored )
Now what cartesian product do is : It gives the set of all ordered pairs ( Giving all possibilities under given circumstances)
SOLUTION :
Here what we will do is perform Cartesian Product of set {-1 , 0 , 1 } with the each i-th dimension and we will do this for all N-dimensions so that no possible neighbor is left behind.
(Just keep in mind to remove the entry with all n-zeroes as it will point to the reference co-ordinate ( who's neighbors we are finding)
We can write a recursive algorithm to do the above task :
algo
func(n : dimension
index : n-tuple)
answer := empty list
for ind in cpower({-1, 0, 1}, n) do
if not (ind is all zeros then)
temp := [index[i] + ind[i] #for i in 1..n]
answer := append(answer, temp)
end
loop
return answer
Here is the recursive algorithm to do that.
I tried my best to explain the question but as this is quite tough problem so if you need any more help or clarification in answer you can comment and I will help you out in best possible way .