785. Is Graph Bipartite?( 判断是否为二分图)

Given an undirected graph, return true if and only if it is bipartite.

Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B.

The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and jexists.  Each node is an integer between 0 and graph.length - 1.  There are no self edges or parallel edges: graph[i]does not contain i, and it doesn't contain any element twice.

Example 1:
Input: [[1,3], [0,2], [1,3], [0,2]]
Output: true
Explanation: 
The graph looks like this:
0----1
|    |
|    |
3----2
We can divide the vertices into two groups: {0, 2} and {1, 3}.
Example 2:
Input: [[1,2,3], [0,2], [0,1,3], [0,2]]
Output: false
Explanation: 
The graph looks like this:
0----1
| \  |
|  \ |
3----2
We cannot find a way to divide the set of nodes into two independent subsets.

说明:1、输入数组中的graph[i],表示顶点i所有相邻的顶点,比如对于例子1来说,顶点0和顶点1,3相连,顶点1和顶点0,2相连,顶点2和结点1,3相连,顶点3和顶点0,2相连。

方法一:bfs
class Solution {
    public static boolean isBipartite(int[][] graph) {
        if(graph.length<=1)
            return true;
        int color[]=new int[graph.length];
        for(int i=0;i<graph.length;i++){
            if(color[i]==0){
                color[i]=1;
                Queue<Integer> queue=new LinkedList<Integer>();
                queue.offer(i);
                while(queue.size()>0){
                    int t1=queue.poll();
                    for(int j=0;j<graph[t1].length;j++){
                        int t2=graph[t1][j];
                        if(color[t2]==0){
                            color[t2]=color[t1]==1?2:1;
                            queue.offer(t2);
                        }
                        else{
                            if(color[t1]==color[t2])
                                return false;
                        }
                    }
                }
            }
        }
        return true;
    }
}

方法二:dfs

class Solution {
    private boolean flag=true;
    public boolean isBipartite(int[][] graph) {
        if(graph.length<=1)  return true;
        int [] color=new int[graph.length];
        for(int i=0;i<graph.length;i++){
            if(color[i]==0){
                color[i]=1;
                dfs(i,graph,color);
                if(!flag){
                    return flag;
                }
            }
        }
        return true;
    }
    void dfs(int pos,int[][] graph,int[] color){
        for(int j=0;j<graph[pos].length;j++){
            int k=graph[pos][j];
            if(color[k]==0){
                color[k]=color[pos]==1?2:1;
                dfs(k,graph,color);
            }else{
                if(color[k]==color[pos]){
                    flag=false;
                    return;
                }
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/shaer/p/10961569.html