- Related Questions & Answers
- Program to find a sublist where first and last values are same in Python
- Python Group tuples in list with same first value
- Python Group elements at same indices in a multi-list
- Number of Ways to Stay in the Same Place After Some Steps in C++
- How can you stay healthy during fasting?
- How can a working mother stay stressfree?
- MySQL group by for separate id without using GROUP BY to remove duplicate column row?
- C# program to separate joined strings in C#
- Group values on same property - JavaScript
- Program to find maximum number enemies will be killed to place a bomb in C++?
- How can I instantiate a dictionary in JavaScript where all keys map to the same value?
- No Enclosing Delimiters in Python
- Program to pack same consecutive elements into sublist in Python
- How to build a string with no repeating character n separate list of characters? in JavaScript
- How to stay young forever?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a number n and a 2D matrix called enemies. Here n indicates there is n people labeled from [0, n - 1]. Now each row in enemies contains [a, b] which means that a and b are enemies. We have to check whether it is possible to partition the n people into two groups such that no two people that are enemies are in the same group.

So, if the input is like n = 4, enemies = [[0, 3],[3, 2]], then the output will be True, as we can have these two groups [0, 1, 2] and [3].

To solve this, we will follow these steps −

graph := an empty adjacency list

for each enemy pair(u, v) in enemies, do

insert v at the end of graph[u]

insert u at the end of graph[v]

color := a new map

Define a function dfs() . This will take u, c := 0 initially

if u is in color, then

return true when color[u] is same as c

color[u] := c

return true when all of dfs(v, c XOR 1) for each v in graph[u] are true

From the main method do the following −

return true when all of (dfs(u) for each u in range 0 to n and if u is not in color) are true

Let us see the following implementation to get better understanding −

class Solution: def solve(self, n, enemies): from collections import defaultdict graph = defaultdict(list) for u, v in enemies: graph[u].append(v) graph[v].append(u) color = {} def dfs(u, c=0): if u in color: return color[u] == c color[u] = c return all(dfs(v, c ^ 1) for v in graph[u]) return all(dfs(u) for u in range(n) if u not in color) ob = Solution() n = 4 enemies = [[0, 3],[3, 2]] print(ob.solve(n, enemies))

4, [[0, 3],[3, 2]]

True

Advertisements