1.判断二分图
给定一个无向图graph,当这个图为二分图时返回true。
如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。
graph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: graph[i] 中不存在i,并且graph[i]中没有重复的值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/is-graph-bipartite
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路一;DFS
class Solution { private: static constexpr int UNCOLORED = 0; static constexpr int RED = 1; static constexpr int GREEN = 2; vector<int> color; bool valid; public: void dfs(int node, int c, const vector<vector<int>>& graph) { color[node] = c;//染成一种颜色 int cNei = (c == RED ? GREEN : RED);//邻居设置为另一种颜色 for (int neighbor: graph[node]) { if (color[neighbor] == UNCOLORED) { dfs(neighbor, cNei, graph);//遍历邻居,如果没染色,染成另一种颜色 if (!valid) { return; //终止条件 } } else if (color[neighbor] != cNei) {//出现一条边两点颜色相同就直接返回false valid = false; return; } } } bool isBipartite(vector<vector<int>>& graph) { int n = graph.size(); valid = true; color.assign(n, UNCOLORED);//先都不染色 for (int i = 0; i < n && valid; ++i) { if (color[i] == UNCOLORED) { dfs(i, RED, graph);//将点i染成红色 } } return valid; } };
思路二:BFS
class Solution { private: static constexpr int UNCOLORED = 0; static constexpr int RED = 1; static constexpr int GREEN = 2; vector<int> color; public: bool isBipartite(vector<vector<int>>& graph) { int n = graph.size(); vector<int> color(n, UNCOLORED); for (int i = 0; i < n; ++i) { if (color[i] == UNCOLORED) { queue<int> q; q.push(i); color[i] = RED; while (!q.empty()) { int node = q.front(); int cNei = (color[node] == RED ? GREEN : RED); q.pop(); for (int neighbor: graph[node]) { if (color[neighbor] == UNCOLORED) { q.push(neighbor); color[neighbor] = cNei; } else if (color[neighbor] != cNei) { return false; } } } } } return true; } };