#K51842. Find Clusters in a Grid

    ID: 29177 Type: Default 1000ms 256MiB

Find Clusters in a Grid

Find Clusters in a Grid

You are given a set of unique coordinates on a 2D grid and two integers \(n\) and \(m\), where \(n\) is the number of characters (points) and \(m\) is the maximum coordinate value. Two characters are considered adjacent if they are directly connected vertically or horizontally. A cluster is a group of one or more characters such that there is a path between any two characters in the group moving only through adjacent positions.

Your task is to group the given coordinates into clusters. For each cluster, the coordinates should be output in lexicographically sorted order. The clusters themselves should be printed in the order they are discovered.

Note: Use breadth-first search (BFS) or depth-first search (DFS) as needed. The adjacency relation is defined by the four cardinal directions:

\(\{(1,0), (-1,0), (0,1), (0,-1)\}\).

inputFormat

The input is read from standard input (stdin) with the following format:

  • The first line contains two integers \(n\) and \(m\), separated by a space.
  • The next \(n\) lines each contain two space-separated integers representing the \(x\) and \(y\) coordinates of a character.

outputFormat

The output is written to standard output (stdout). For each cluster discovered, output its coordinates in lexicographical order. Each coordinate is printed on a new line in the format: (x, y). Separate different clusters by an empty line.

## sample
5 10
1 1
2 1
1 2
3 4
4 4
(1, 1)

(1, 2) (2, 1)

(3, 4) (4, 4)

</p>