public static int FindCellIndex(Point position, List<VoronoiCell> cells, List<VoronoiCell>[,] cellGrid, int gridCellSize, int searchDepth = 1) { int closestDist = int.MaxValue; VoronoiCell closestCell = null; int gridPosX = position.X / gridCellSize; int gridPosY = position.Y / gridCellSize; for (int x = Math.Max(gridPosX - searchDepth, 0); x <= Math.Min(gridPosX + searchDepth, cellGrid.GetLength(0) - 1); x++) { for (int y = Math.Max(gridPosY - searchDepth, 0); y <= Math.Min(gridPosY + searchDepth, cellGrid.GetLength(1) - 1); y++) { for (int i = 0; i < cellGrid[x, y].Count; i++) { int dist = MathUtils.DistanceSquared( (int)cellGrid[x, y][i].Site.Coord.X, (int)cellGrid[x, y][i].Site.Coord.Y, position.X, position.Y); if (dist > closestDist) continue; closestDist = dist; closestCell = cellGrid[x, y][i]; } } } return cells.IndexOf(closestCell); }