[英]using dfs to check if graph is bipartite
class graph{
void DFSutil(int v);
public:
map<int, vector<int> > adj;
map<int, bool> visited;
map<int, int> color;
int twoteams = 1;
void DFS();
void addEdge(int u,int v);
};
此函數為圖形添加邊
void graph::addEdge(int u,int v){
adj[u].push_back(v);
}
深度優先搜索功能。 我試圖將孩子着色為 !parent (以防我沒有錯):如果孩子和父母的顏色相同,這意味着該圖不是二部圖
void graph::DFSutil(int v){
visited[v] = true;
for (auto i:adj[v]){
if(visited[i]==false){
color[i] = !color[v];
DFSutil(i);
}
else if(color[i]==color[v]){
twoteams = 0;
return;
}
}
}
如果圖有多個連通分量
void graph::DFS(){
for (auto i:adj){
if(!visited[i.first]) DFSutil(i.first);
}
}
該圖給出為:B(向量):[[1,2],[1,3]...] 邊:1-->2, 1-->3...
int Solution::solve(int A, vector<vector<int> > &B) {
graph g;
g.addEdge(B[0][0],B[0][1]);
g.color[B[0][0]] = 1;
int n = B.size();
for (int i=1;i<n;++i){
g.addEdge(B[i][0],B[i][1]);
}
g.DFS();
return g.twoteams;
}
為什么它不檢查圖形是否是二部圖。 color 將節點的顏色存儲為 0 或 1; 如果不是雙向的,則返回 0,否則返回 1
為了確定一個圖是否是二部圖,確定最大集團的數量正好是兩個就足夠了。
這是查找最大團的偽代碼
LOOP
CONSTRUCT empty current set
SELECT V arbitrary vertex
add V to current set
remove V from graph
LOOP // while set is growing
added_to_set = false
LOOP V over vertices in graph
LOOP Vset over current set
IF Vset connected to V
add V to current set
remove V from graph
added_to_set = true
break;
IF added_to_set == false
break; // the set is maximal
ADD current set to list of sets
IF graph has no remaining vertices
OUTPUT sets found
STOP
有關此的 C++ 實現,請參閱https://github.com/JamesBremner/PathFinder2/blob/dbd6ff06edabd6a6d35d5eb10ed7972dc2d779a6/src/cPathFinder.cpp#L483 上的代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.