1. 程式人生 > >785. Is Graph Bipartite? - Medium

785. Is Graph Bipartite? - Medium

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 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.

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 Coloring (by DFS/BFS): color a node as red, and then color all its neighbors as blue recursively. if there's any conflict, return false.

染色法 Graph Coloring (by DFS) 將相連的兩個頂點染成不同的顏色,一旦在染的過程中發現有兩連的兩個頂點已經被染成相同的顏色,說明不是二分圖。 -> 使用兩種顏色,分別用1和-1來表示,初始時每個頂點用0表示未染色  -> 遍歷每一個頂點,如果該頂點未被訪問過,呼叫遞迴函式,如果返回false,說明不是二分圖,直接返回false;              如果迴圈退出後沒有返回false,則返回true。 -> 在遞迴函式中,如果當前頂點已經染色:如果該頂點的顏色和將要染的顏色相同,則返回true;否則返回false。                           如果沒被染色,則將當前頂點染色(-1*color: 將相鄰點染成不同顏色),然後再遍歷與該頂點相連的所有的頂點,呼叫遞迴函式,如果返回false了,則當前遞迴函式的返回false,迴圈結束返回true.   time: O(V+E), space: O(V+E)
class Solution {
    int[] colors;
    public boolean isBipartite(int[][] graph) {
        int n = graph.length;
        colors = new int[n];
        for(int i = 0; i < n; i++) {
            if(colors[i] == 0 && !dfs(graph, i, 1))
                return false;
        }
        return true;
    }
    
    private boolean dfs(int[][] graph, int node, int color) {
        if(colors[node] != 0)
            return colors[node] == color ? true: false;
        else {
            colors[node] = color;
            for(int j : graph[node]) {
                if(!dfs(graph, j, -color))
                    return false;
            }
        }
        return true;
    }
}