Problem SOLUTION CODECHEF
You are given a simple undirected graph with � vertices and � edges.
Find the smallest non-negative integer � such that for every vertex � (1≤�≤�), there exists a walk of length exactly � from 1 to �.
If no such integer exists, print −1 instead.
Notes:
- It is allowed to repeat both vertices and edges in a walk.
- The length of a walk equals the number of edges in it.
Input Format
- The first line of input will contain a single integer �, denoting the number of test cases.
- Each test case consists of multiple lines of input.
- The first line of each test case contains two space-separated integers � and � — the number of vertices and edges of the graph, respectively.
- The next � lines describe the edges. The �-th of these � lines contains two space-separated integers �� and ��, denoting an edge between �� and ��.
Output Format
For each test case, output on a new line the answer: the minimum value of � such that there exists a length-� walk from 1 to every other vertex; or −1 if no such � exists.
Constraints
- 1≤�≤103
- 1≤�≤105
- 1≤�≤min(�⋅(�−1)2,105)
- 1≤��,��≤�
- ��≠�� for each 1≤�≤�.
- Each unordered pair (�,�) appears at most once.
- The sum of � across all test cases doesn’t exceed 105.
- The sum of � across all test cases doesn’t exceed 105.
Sample 1:
2 3 3 1 2 2 3 1 3 3 2 1 2 1 3
2 -1
Explanation:
Test case 1: We have the following length-2 walks reaching every vertex:
- 1→2→3 to reach 3.
- 1→3→2 to reach 2.
- 1→2→1 to reach 1.
Note that we reuse an edge here, which is allowed.
Test case 2: It can be proved that no integer � satisfying the condition exists.
SOLUTION
def find_minimum_K(N, M, edges):
def dfs(u, k):
visited[u] = True
min_K[u] = k
for v in graph[u]:
if not visited[v]:
dfs(v, max(k, min_K[u] + 1))
graph = [[] for _ in range(N)]
min_K = [float(‘inf’)] * N
for u, v in edges:
graph[u – 1].append(v – 1)
graph[v – 1].append(u – 1)
visited = [False] * N
dfs(0, 0)
if all(visited):
return max(min_K)
else:
return -1
# Input
T = int(input())
for _ in range(T):
N, M = map(int, input().split())
edges = [list(map(int, input().split())) for _ in range(M)]
result = find_minimum_K(N, M, edges)
print(result)