Another possibility, related to the foregoing, is to use a sparse-matrix structure to store 1
values at the location of all of your points and 0
values elsewhere.
While nice libraries exist for this, you can fake it by coming up with a hash which combines your x
and y
coordinates. In C++ that looks something like:
std::unordered_set< std::pair<int,int> > hashset;
Presize the hashtable so it is perhaps 30-50% larger than you need to avoid expensive rehashing.
Add all the points to the hashset; this takes O(n)
time.
Now, the interaction distance L(given)
defines a diamond about a center point. You could pregenerate a list of offsets for this diamond. For instance, if L=2
, the offsets are:
int dx[]={0,-2,-1,0,1,2, 1,0,-1};
int dy[]={0, 0, 1,2,1,0,-1,2,-1};
Now, for each point, loop over the list of offsets and add them to that point's coordinates. This generates an implicit list of locations where neighbours could be. Use the hashset to check if that neighbour exists. This takes O(n)
time and is efficient if 8L << N
(with some qualifications about the number of neighbours reachable from the first node).