I have solved problem 10608 on UVA Online Judge using Python 3.5.1. My solution works, but it takes too long to run when the online judge evaluates it.
Problem
There is a town with N citizens. It is known that some pairs of people are friends. According to the famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends and B and C are friends then A and C are friends, too. Your task is to count how many people there are in the largest group of friends.
Input
Input consists of several datasets. The first line of the input consists of a line with the number of test cases to follow.
The first line of each dataset contains tho numbers N and M, where N is the number of town’s citizens (1 ≤ N ≤ 30000) and M is the number of pairs of people (0 ≤ M ≤ 500000), which are known to be friends. Each of the following M lines consists of two integers A and B (1 ≤ A ≤ N, 1 ≤ B ≤ N, A ̸= B) which describe that A and B are friends. There could be repetitions among the given pairs.
Output
The output for each test case should contain (on a line by itself) one number denoting how many people there are in the largest group of friends on a line by itself.
Sample Input
2
3 2
1 2
2 3
10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 1
1 2
9 10
8 9
Sample Output
3
7
testCases = int(input())
for x in range(testCases):
temp = input().split()
N = int(temp[0])
M = int(temp[1])
nodes = []
edges = []
for _ in range(M):
temp = input().split()
A = int(temp[0])
B = int(temp[1])
edges.append([A, B])
counter = 0
for y in range(N):
counter += 1
nodes.append(counter)
hashmap = {}
for h in range(len(nodes)):
neighbours = []
for j in range(len(edges)):
if edges[j].__contains__(nodes[h]):
index_of_node = edges[j].index(nodes[h])
if index_of_node == 0:
neighbours.append(edges[j][1])
hashmap[h + 1] = neighbours
else:
neighbours.append(edges[j][0])
hashmap[h + 1] = neighbours
current_group = 0
highest_group = 0
def reset_array():
visited = []
for _ in range(1, N + 2):
visited.append(False)
return visited
visited = reset_array()
def dfs(at):
if visited[at]:
return
else:
visited[at] = True
global current_group
current_group += 1
if at in hashmap:
neighbours = hashmap[at]
for next in neighbours:
dfs(next)
else:
return
counter = 0
for i in range(len(nodes)):
dfs(i + 1)
if current_group > highest_group:
highest_group = current_group
visited = reset_array()
current_group = 0
print(highest_group)