Optimized CountNeighbour function