-
-
Notifications
You must be signed in to change notification settings - Fork 611
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
today's contribution, medium problem, graph bipartation
- Loading branch information
Sherali Obidov
committed
Aug 25, 2018
1 parent
ea58888
commit 55c3f41
Showing
2 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package problems.medium; | ||
|
||
import java.util.*; | ||
|
||
/** | ||
* Why Did you create this class? what does it do? | ||
*/ | ||
public class PossibleBipartition { | ||
public boolean possibleBipartition(int n, int[][] dislikes) { | ||
Map<Integer, Boolean> bools = new HashMap<>(); | ||
Map<Integer, Set<Integer>> map = new HashMap<>(); | ||
for (int i = 0; i < dislikes.length; i++) { | ||
int ii = dislikes[i][0]; | ||
int jj = dislikes[i][1]; | ||
Set<Integer> set = map.getOrDefault(ii, new HashSet<>()); | ||
set.add(jj); | ||
map.put(ii, set); | ||
set = map.getOrDefault(jj, new HashSet<>()); | ||
set.add(ii); | ||
map.put(jj, set); | ||
} | ||
bools.put(1, true); | ||
Queue<Integer> q = new LinkedList<>(); | ||
Set<Integer> visited = new HashSet<>(); | ||
q.add(1); | ||
while (!q.isEmpty()) { | ||
Integer current = q.remove(); | ||
visited.add(current); | ||
if (map.get(current) != null) { | ||
for (Integer nei : map.get(current)) { | ||
if (!visited.contains(nei)) { | ||
if (bools.get(nei) == bools.get(current)) { | ||
return false; | ||
} | ||
q.add(nei); | ||
bools.put(nei, !bools.get(current)); | ||
} | ||
} | ||
} | ||
} | ||
return true; | ||
|
||
} | ||
} |