1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { public boolean isBipartite(int[][] graph) { int n = graph.length; int[] color = new int[n];
for(int i = 0; i < n; i++){ if(color[i] == 0){ color[i] = 1; } if(!dfs(i, 0, graph, color)){ return false; } } return true; }
public boolean dfs(int cur, int k, int[][] graph, int[] color){
for(int i = k; i < graph[cur].length; i++){ int next = graph[cur][i];
if(color[next] == 0){ color[next] = 3 - color[cur]; }else if(color[next] == color[cur]){ return false; }else { continue; }
if(!dfs(next, 0, graph, color)){ return false; } } return true; } }
|