#C3224. Capture the Castles
Capture the Castles
Capture the Castles
You are given N castles (numbered from 1 to N) and M bidirectional roads connecting them. In one move, you can travel along one road from a castle to an adjacent castle.
The task is to determine the minimum number of moves required to capture all the castles if you start from the castle that maximizes your reach. Equivalently, you need to compute the diameter of the undirected graph, which is defined as:
$$D = \max_{1 \leq i,j \leq N} d(i,j)$$
where \(d(i,j)\) is the shortest distance between castles \(i\) and \(j\). If there are no roads or if there is only one castle, the answer is 0.
Note that although one might expect that starting from an optimal castle minimizes the maximum moves (i.e. the graph radius), the answer required here is the graph diameter as demonstrated by the examples below.
inputFormat
The input is given via standard input (stdin) and has the following format:
- The first line contains two integers N and M, representing the number of castles and the number of roads respectively.
- The next M lines each contain two integers u and v, indicating that there is a bidirectional road connecting castle u and castle v.
You can assume that the data represents a valid undirected graph.
outputFormat
Output a single integer on standard output (stdout) which is the minimum number of moves required to capture all the castles (i.e. the diameter of the graph). If no roads exist or if there is only one castle, output 0.
## sample4 4
1 2
2 3
3 4
4 1
2