只允许使用两种颜色,对图进行着色,相邻点的颜色一定要不同,问是否能成功。
比较经典的邻接表图算法。
用dfs来实现。对于每一个节点的邻接节点,依次进行dfs染色,若有一个染色失败(两个点颜色相同),就返回失败
对所有点循环过后,若没有失败,就返回成功。 例子里面的表来自《挑战程序竞赛》第二版98页。
//
// 099_binary garph.cpp
// changlle
//
// Created by user on 12/31/15.
// Copyright (c) 2015 user. All rights reserved.
//
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<int> G[10];
int color[10];
int V=4;
bool dfs (int s, int c) {
color[s]=c; // 对点s染色
for (int i=0;i<G[s].size();i++) { //考察s的邻居
if (color[G[s][i]]==c)
return false; //如果颜色一样就返回失败
if (color[G[s][i]]==0)
{
bool suc=dfs(G[s][i],-1*c); //如果没有染色,就染色,并且返回结果
if (suc==false) //如果染色失败,立即返回false
return false;
}
}
return true; //如果所有邻居成功,次节点也成功。
}
int main (){
G[0].push_back(1);
G[0].push_back(3);
G[1].push_back(0);
G[1].push_back(2);
G[2].push_back(1);
G[2].push_back(3);
G[3].push_back(0);
G[3].push_back(2);
fill(color, color+10,0);
string suc="yes";
for (int i=0;i<V;i++){
if (color[i]==0)
if (dfs(i,1)==false)
{
suc="no";
break;
}
}
cout<<suc<<endl;
for (int i=0;i<V;i++)
cout<<color[i]<<" ";
return 0;
}