785. Is Graph Bipartite?

https://leetcode.com/problems/is-graph-bipartite/discuss/115487/Java-Clean-DFS-solution-with-Explanation

 

 

 1 class Solution {
 2     int[] colors;
 3     public boolean isBipartite(int[][] graph) {
 4         if(graph.length == 0) return false;
 5         colors = new int[graph.length];
 6         for(int i = 0; i < graph.length; i++){
 7             if(colors[i] == 0){    
 8                 if(!isValid(graph, i, 1)){
 9                     System.out.println(i);
10                     return false;
11                 }
12             }
13         }
14         return true;
15     }
16     
17     public boolean isValid(int[][] graph, int i, int color){
18        if(colors[i] != 0){
19             return colors[i] == color;
20         }
21         colors[i] = color;
22         for(int num : graph[i]){
23             if(!isValid(graph, num, -color)){
24                 return false;
25             }
26         }
27         return true;
28     }
29 }

 

posted @ 2018-10-24 10:25  jasoncool1  阅读(161)  评论(0)    收藏  举报