Program to group a set of points into k different groups in Python


Suppose we have a list of points and a number k. The points are in the form (x, y) representing Cartesian coordinates. We can group any two point p1 and p2 if the Euclidean distance between them is <= k, we have to find total number of disjoint groups.

So, if the input is like points = [[2, 2],[3, 3],[4, 4],[11, 11],[12, 12]], k = 2, then the output will be 2, as it can make two groups: ([2,2],[3,3],[4,4]) and ([11,11],[12,12])

To solve this, we will follow these steps −

  • Define a function dfs() . This will take i

  • if i is in seen, then

    • return

    • insert i into seen

    • for each nb in adj[i], do

      • dfs(nb)

      • From the main method, do the following−

      • adj := a map

      • n := size of points

      • for j in range 0 to n, do

        • for i in range 0 to j, do

          • p1 := points[i]

          • p2 := points[j]

          • if Euclidean distance between p1 and p2 < k, then

            • insert j at the end of adj[i]

            • insert i at the end of adj[j]

      • seen := a new set

      • ans := 0

      • for i in range 0 to n, do

        • if i not seen, then

          • ans := ans + 1

          • dfs(i)

      • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

from collections import defaultdict
class Solution:
   def solve(self, points, k):
      adj = defaultdict(list)

      n = len(points)
      for j in range(n):
         for i in range(j):
            x1, y1 = points[i]
            x2, y2 = points[j]
            if (x1 - x2) ** 2 + (y1 - y2) ** 2 <= k ** 2:
               adj[i].append(j)
               adj[j].append(i)

      seen = set()
      def dfs(i):
         if i in seen:
            return
         seen.add(i)
         for nb in adj[i]:
            dfs(nb)

      ans = 0
      for i in range(n):
         if i not in seen:
            ans += 1
            dfs(i)
      return ans
ob = Solution()
points = [
[2, 2],
[3, 3],
[4, 4],
[11, 11],
[12, 12]
]
k = 2
print(ob.solve(points, k))

Input

[[2, 2],[3, 3],[4, 4],[11, 11],[12, 12]],2

Output

2

Updated on: 08-Oct-2020

545 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements