Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Given a list of pair of "unrelated images", we need to know whether we can divide the images into two groups
- such that no two unrelated images are in the same group.
- Case 1
- I_1 <-> I_4
- I_4 <-> I_8
- I_8 <-> I_2
- Result:
- Group 1 -> [I_1, I_8]
- Group 2 -> [I_4, I_2]
- Case 2
- I_1 <-> I_4
- I_4 <-> I_8
- I_8 <-> I_1
- """
- from collections import defaultdict
- from typing import List, Tuple
- class Solution:
- def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> Tuple[bool, List[int], List[int]]:
- # Constants defined for color drawing
- BLUE, GREEN = 1, -1
- def draw(person_id, color):
- # Color the current person
- color_of[person_id] = color
- # Append the person to the respective group
- if color == BLUE:
- group_one.append(person_id)
- else:
- group_two.append(person_id)
- # Iterate through all persons disliked by the current person
- for the_other in dislike_table[person_id]:
- if color_of[the_other] == color:
- # Conflict found, return False
- return False
- if color_of[the_other] == 0 and not draw(the_other, -color):
- # If the other person is uncolored, color them with the opposite color
- return False
- return True
- # Simple case checks
- if N == 1 or not dislikes:
- return True, list(range(1, N + 1)), []
- # Adjacency list for dislikes
- dislike_table = defaultdict(list)
- # Color mapping for persons
- color_of = defaultdict(int)
- # Groups to store the result
- group_one = []
- group_two = []
- # Build the dislike graph
- for p1, p2 in dislikes:
- dislike_table[p1].append(p2)
- dislike_table[p2].append(p1)
- # Try to color the graph
- for person_id in range(1, N + 1):
- if color_of[person_id] == 0:
- # Clear the groups for new DFS/BFS
- group_one = []
- group_two = []
- if not draw(person_id, BLUE):
- return False, [], [] # Return false if unable to color
- return True, group_one, group_two
- def solve_return_all_groups():
- # Example cases
- case1_n = 8
- case1_dislikes = [[1, 4], [4, 8], [8, 2]]
- case2_n = 8
- case2_dislikes = [[1, 4], [4, 8], [8, 1]]
- solution = Solution()
- result_case1 = solution.possibleBipartition(case1_n, case1_dislikes)
- result_case2 = solution.possibleBipartition(case2_n, case2_dislikes)
- print(f"Case 1: Can be partitioned: {result_case1[0]}, Group 1: {result_case1[1]}, Group 2: {result_case1[2]}") # Expected: True
- print(f"Case 2: Can be partitioned: {result_case2[0]}, Group 1: {result_case2[1]}, Group 2: {result_case2[2]}") # Expected: False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement