Given an adjacency list of students and their enemies, write an algorithm that finds a satisfactory pair of teams, or returns False if none exists.
For example, given the following enemy graph you should return the teams {0, 1, 4, 5} and {2, 3}.
students = {
0: [3],
1: [2],
2: [1, 4],
3: [0, 4, 5],
4: [2, 3],
5: [3]
}
On the other hand, given the input below, you should return False.
students = {
0: [3],
1: [2],
2: [1, 3, 4],
3: [0, 2, 4, 5],
4: [2, 3],
5: [3]
}
Solution
The Solution is straight forward. We maintain Two Lists representing two teams. At the same time we also maintain Two Sets representing the enemies of the teams.We iterate through all the members one by one. We insert the member into eligible list and update the enemies set as well. If we can successfully insert all the members, then we have our solution. If we are unbale to insert all memebers, then the two teams cannot be formed.
WARNING!!
The solution is not as straight forward as it sounds. It may be possible that the team member inserted previously into any of the list might cause conflict and hence result might not be possible.
For following example, if we iterate in the order 0, 1, 2, 3, 4, 5 we will enounter 4 is enemies in both the team.
students = {
0: [3],
1: [5],
2: [4],
3: [0, 4, 5],
4: [2, 3],
5: [3]
}
But it has valid team division and that is: {0, 4, 5} and {1, 2, 3}.
Implementation
Following is implementation with back tracking.