1. 程式人生 > 實用技巧 >785. Is Graph Bipartite?

785. Is Graph Bipartite?

Given an undirectedgraph, returntrueif and only if it is bipartite.

Recall that a graph isbipartiteif we can split it's set of nodes into two independentsubsets 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 indexesj

for which the edge between nodesiandjexists. Each node is an integer between0andgraph.length - 1. There are no self edges or parallel edges:graph[i]does not containi, 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.

Note:

  • graphwill have length in range[1, 100].
  • graph[i]will contain integers in range[0, graph.length - 1]
    .
  • graph[i]will not containior duplicate values.
  • The graph is undirected: if any elementjis ingraph[i], theniwill be ingraph[j].
class Solution {
    public boolean isBipartite(int[][] graph) {
        //BFS
        // 0(not meet), 1(black), 2(white)
        int[] visited = new int[graph.length];
        
        for (int i = 0; i < graph.length; i++) {
            if (graph[i].length != 0 && visited[i] == 0) {
                visited[i] = 1;
                Queue<Integer> q = new LinkedList<>();
                q.offer(i);
                while(! q.isEmpty()) {
                    int current = q.poll();
                    for (int c: graph[current]) {

                            if (visited[c] == 0) {
                                visited[c] = (visited[current] == 1) ? 2 : 1;
                                q.offer(c);
                            } else {
                                if (visited[c] == visited[current]) return false;
                            }
                    }
                }                                       
            }
        }        
        return true;
    }
}

BFS,塗色法,對每個點塗色,然後對current它所有的adjacent node塗成相反顏色,只要有一步的檢查裡和current顏色相同就返回false

https://www.youtube.com/watch?v=670Gn4e89B8