Advertisement
Guest User

Grokking #229

a guest
Aug 5th, 2022
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. class Solution {
  2.    
  3.     /*
  4.       Choose no color = -1
  5.       RED color = 0; BLUE color = 1
  6.       We can switch the colors easily by "^" operator
  7.     */
  8.     static final int NO_COLOR = -1;    
  9.     List<List<Integer>> graph;
  10.     int[] colors;
  11.    
  12.    
  13.     public boolean possibleBipartition(int n, int[][] dislikes) {
  14.         // create graph
  15.         graph = new ArrayList<>();                
  16.         colors = new int[n + 1];
  17.         Arrays.fill(colors, NO_COLOR);
  18.        
  19.         for (int i = 0; i <= n; i++) {
  20.             graph.add(new ArrayList<Integer>());
  21.         }
  22.        
  23.         for (int[] dislike : dislikes) {
  24.             graph.get(dislike[0]).add(dislike[1]);
  25.             graph.get(dislike[1]).add(dislike[0]);
  26.         }
  27.        
  28.         // check bipartite graph
  29.         for (int at = 0; at <= n; at++) {
  30.             // if vertex has no color, start coloring with 0 color
  31.             if (colors[at] == NO_COLOR && !canColor(at, 0)) {
  32.                 return false;
  33.             }
  34.         }
  35.        
  36.         return true;
  37.     }
  38.    
  39.     boolean canColor(int at, int color) {        
  40.         colors[at] = color;
  41.         for (int to : graph.get(at)) {
  42.             // if neighbor vertex has same color with current vertex, return false
  43.             if (colors[to] == color) {
  44.                 return false;
  45.             }
  46.            
  47.             // color neighbor vertex with alternative color
  48.             // 0 ^ 1 = 1
  49.             // 1 ^ 1 = 0
  50.             if (colors[to] == NO_COLOR && !canColor(to, color ^ 1)) {
  51.                 return false;
  52.             }
  53.         }
  54.         return true;
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement