Civilization
Time limit2sMemory limit512 MB
Given K starting cells in an N x N grid where civilization spreads one step per year in all four directions, find the minimum number of years until all seeds merge into a single civilization.
- Level
Medium7 of 10
- Topics
- Graph, BFS, Binary search, Union-find
- Solved
- No attempts yet
Problem
A civilization can grow on its own, and two different civilizations can meet and merge into one. Starting from that assumption, you simulate how the civilizations of a world develop.
The world is a two-dimensional space of size . It holds unit squares along each side. The bottom left square is at position and the top right square is at position . Two squares and are adjacent when exactly one of the following holds.
- and .
- and .
Civilizations start at distinct squares. Every square is either civilized or wild, and every starting square is civilized. If two starting squares are adjacent, their civilizations are merged from the beginning. Each year every civilized square spreads its civilization to the squares next to it. If square is civilized, then one year later , , and are all civilized, as long as they stay inside the world. When two adjacent squares hold different civilizations, or when more than one civilization reaches the same square, those civilizations merge. Merging is transitive: if A merges with B and B merges with C, then A and C are the same civilization.

The picture shows the case with starting squares , , and . The squares and are adjacent, so their civilizations are merged from the start. The left side is the civilized area after one year and the right side is the area after two years. After two years all four civilizations form a single one. The civilization from and the one from never touch each other directly; they merge through the civilization of and .
Given the size of the world and the number and positions of the starting squares, write a program that computes the smallest number of years needed until all civilizations become one.
Input
The first line contains the size of the world () and the number of starting squares (). Each of the next lines contains two integers and , the position of one starting square (). The starting positions are all different.
Output
Print a single integer, the smallest number of years until all civilizations merge into one.