Is Graph Bipartite? 07/30

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 iand j exists. 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.

  • graph will have length in range [1, 100].

  • graph[i] will contain integers in range [0, graph.length - 1].

  • graph[i] will not contain i or duplicate values.

  • The graph is undirected: if any element j is in graph[i], then i will be in graph[j].

Have you met this question in a real interview? Yes

Example

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.

这道题博主在最开始做的时候,看了半天,愣是没弄懂输出数据的意思,博主开始以为给的是边,后来发现跟图对应不上,就懵逼了,后来是通过研究论坛上大神们的解法,才总算搞懂了题目的意思,原来输入数组中的graph[i],表示顶点i所有相邻的顶点,比如对于例子1来说,顶点0和顶点1,3相连,顶点1和顶点0,2相连,顶点2和结点1,3相连,顶点3和顶点0,2相连。这道题让我们验证给定的图是否是二分图,所谓二分图,就是可以将图中的所有顶点分成两个不相交的集合,使得同一个集合的顶点不相连。为了验证是否有这样的两个不相交的集合存在,我们采用一种很机智的染色法,大体上的思路是要将相连的两个顶点染成不同的颜色,一旦在染的过程中发现有两连的两个顶点已经被染成相同的颜色,说明不是二分图。这里我们使用两种颜色,分别用1和-1来表示,初始时每个顶点用0表示未染色,然后遍历每一个顶点,迭代的解法,整体思路还是一样的,还是遍历整个顶点,如果未被染色,则先染色为1,然后使用BFS进行遍历,将当前顶点放入队列queue中,然后while循环queue不为空,取出队首元素,遍历其所有相邻的顶点,如果相邻顶点未被染色,则染成和当前顶点相反的颜色,然后把相邻顶点加入queue中,否则如果当前顶点和相邻顶点颜色相同,直接返回false,循环退出后返回true,参见代码如下::

public class Solution {
    /**
     * @param graph: the given undirected graph
     * @return:  return true if and only if it is bipartite
     */
    public boolean isBipartite(int[][] graph) {
        // Write your code here
        
        int[] colors = new int[graph.length];
        
         Queue<Integer> queue = new LinkedList<>();
         
        for (int i = 0; i < graph.length ;i++ ){
            if(colors[i] != 0) continue;
            colors[i] = 1;
           
            queue.offer(i);
            
            while(!queue.isEmpty()){
                int t = queue.poll();
                for(int j = 0; j < graph[t].length;j++){
                    if(colors[graph[t][j]] == 0){
                        colors[graph[t][j]] = -1* colors[t];
                        queue.offer(graph[t][j]);
                    }else{
                        if(colors[graph[t][j]] == colors[t]){
                            return false;
                        }
                    }
                }
                
            }
            
        } 
        
        return true;
    
    }
}

Last updated