Problem statement

https://binarysearch.com/problems/Group-Points/

Solution

Just use dfs to find connected components.

Complexity

It is O(n^2) for time and O(n) for space.

Code

class Solution:
    def solve(self, P, k):
        n, comp = len(P), 0
        visited = [0]*n
        
        def dfs(x):
            if visited[x]: return
            visited[x] = 1
            for i in range(n):
                if (P[x][0] - P[i][0])**2 + (P[x][1] - P[i][1])**2 <= k*k:
                    dfs(i)
        
        for i in range(n):
            if visited[i] == 0:
                dfs(i)
                comp += 1
        
        return comp