#K72702. Connected Kingdom
Connected Kingdom
Connected Kingdom
You are given a kingdom with n cities and m bidirectional roads connecting pairs of cities. The kingdom is said to be "connected" if there exists a path between every pair of cities through the available roads.
Your task is to determine whether the given kingdom is fully connected. More formally, given an integer n representing the number of cities and an integer m representing the number of roads, followed by m pairs of integers where each pair represents a road between two cities, output YES
if every city is reachable from every other city, or NO
otherwise.
Cities are numbered from 1 to n.
The connectivity check can be visualized with the graph connectivity problem in graph theory. One of the tools to help you is the Breadth First Search (BFS) or Depth First Search (DFS) algorithm. The condition for full connectivity is mathematically given by:
\( |Visited| = n \)
inputFormat
The first line of input contains two space-separated integers representing n
(the number of cities) and m
(the number of roads).
The following m
lines each contain two space-separated integers a
and b
, meaning there is a bidirectional road between city a
and city b
.
outputFormat
Output a single line containing either YES
if the kingdom is fully connected or NO
if it is not.
5 5
1 2
2 3
3 4
4 5
2 4
YES
</p>