Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation…
- User
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates. Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2 2 1 1 2
Output
1
Input
2 2 1 4 1
Output
0
Assistant
n = int(input()) points = [tuple(map(int, input().split())) for _ in range(n)] adj = [[] for _ in range(n)] for i in range(n): for j in range(i + 1, n): a, b = points[i], points[j] same_x = a[0] == b[0] same_y = a[1] == b[1] if same_x or same_y: blocked = False if same_x: y_min = min(a[1], b[1]) y_max = max(a[1], b[1]) for k in range(n): if k == i or k == j: continue x, y = points[k] if x == a[0] and y_min < y < y_max: blocked = True break else: x_min = min(a[0], b[0]) x_max = max(a[0], b[0]) for k in range(n): if k == i or k == j: continue x, y = points[k] if y == a[1] and x_min < x < x_max: blocked = True break if not blocked: adj[i].append(j) adj[j].append(i) visited = [False] * n components = 0 for i in range(n): if not visited[i]: components += 1 stack = [i] visited[i] = True while stack: node = stack.pop() for neighbor in adj[node]: if not visited[neighbor]: visited[neighbor] = True stack.append(neighbor) print(components - 1)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.