[Week 3] LeetCode 785. Is Graph Bipartite?

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

Note:

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

题解:

判断一个图是否是二部图,最常见的方法就是染色法,即先选取一个点染为任意颜色,然后遍历这个点的边,对其邻点进行染色(与这个点不同的颜色),如果发现其邻点已染色,则有两种情况:

  1. 与该点同色,则说明该图不是二部图
  2. 与该点异色,则说明之前其邻点已经遍历过了

Ok,想法很简单,用 BFS 或 DFS 都能简单地完成这个任务,只是需要注意这个图可能不是一个连通图,所以应该从每个节点开始遍历,避免漏掉某些节点。

Code:

/*
 * 0 代表未染色,1 和 -1 表示两种不同的颜色
 */
bool isBipartite(vector<vector<int> >& graph) {
	vector<int> colorOfNode(graph.size(), 0);
	
	for (int k = 0; k < graph.size(); ++k) {

		queue<int> openList;
		if (colorOfNode[k] == 0) openList.push(k);

		while (!openList.empty()) {
			int u = openList.front();
			openList.pop();
			if (colorOfNode[u] == 0) colorOfNode[u] = -1;

			for (int i = 0; i < graph[u].size(); ++i) {
				int v = graph[u][i];
				if (colorOfNode[v] == colorOfNode[u]) return false;
				else if (colorOfNode[v] == -colorOfNode[u]) continue;
				else {
					colorOfNode[v] = -colorOfNode[u];
					openList.push(v);
				}
			}

		}
	}
	return true;
}

复杂度分析:

每个节点只会被遍历一次,然后与节点相连的边大部分情况下都会被遍历一次(这里指 u->v ,因为这个图本身是个无向图),所以复杂度是 O(|V|+|E|)。所以这是一个线性判断一个图是否为二部图的算法。

你可能感兴趣的:(LeetCode,c++,算法,Graph)