added optimization for checking only neighbors and neighbors of neighbors