Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to separate persons where no enemies can stay in same group in Python
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 −
Example
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))
Input
4, [[0, 3],[3, 2]]
Output
True