Official

E - Round Trip Editorial by en_translator


In a path satisfying \((x_0, y_0), \dots, (x_n, y_n)\), two squares \((x_1, y_1)\) and \((x_{n-1}, y_{n-1})\) are both adjacent to the starting square, and \((x_1, y_1) \neq (x_{n-1}, y_{n-1})\). Therefore, if a desired path exists, then there is a path consisting only of road square (excluding the starting one) that connects two different squares adjacent to the starting square. Conversely, if such a path \((x'_1, y'_1), \dots, (x'_m, y'_m)\) exists, then it always holds that \(m \geq 3\), so the path \((r_s, c_s), (x'_1, y'_1), \dots, (x'_m, y'_m), (r_s, c_s)\) has a length \(4\) or greater, where \((r_s, c_s)\) is the starting square, so the path satisfies the conditions.

Therefore, it is sufficient to inspect all (at most \(6\)) pairs of different squares adjacent to the starting square to check if there is a path connecting those squares consisting only of road squares. This can be implemented with a Breadth-First Search or Union-Find.

Sample Code (C++)

posted:
last update: