"四染色"问题: 用不多于四种颜色对地图着色,使相邻的区域不重色。
算法思想: 从第一个区域开始染色,每一个区域依次用颜色1,2,3,4进行试探,如果当前所试探的颜色与周围区域都不同色,则用栈记录该区域色数,否则用下一色数继续试探;如果四种颜色都与相邻区域重色,那么需要退栈,修改栈顶色数,即更改上一区域的颜色继续试探。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
//地图四染色问题,首先定义了六个国家,用邻接矩阵表示了国家之间的关系等于1意味着相邻
vector<int> color; //存储了从第一个国家开始的颜色
int s[6][6] =
{
{ 0, 1, 1, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1 },
{ 1, 1, 0, 1, 1, 0 },
{ 0, 1, 1, 0, 1, 0 },
{ 0, 1, 1, 1, 0, 1 },
{ 1, 1, 0, 0, 1, 0 }
}; //存储了不同国家的邻接关系
void make_color()
{
int c = 1;
int city = 0;
color.push_back(c);
while (city < 5)
{
c = 0;
c++;
city++;
color.push_back(c);
while (true)
{
for (int i = 0; i < city; i++)
{
if (s[city][i] * c == color[i]) //如果等于就说明相邻且颜色相同
{
c = color.back();
color.pop_back();
c++;
color.push_back(c);
i = 0;
continue;
}
}
break;
}
}
}
int main(void)
{
make_color();
for (auto it : color)
{
cout << "颜色编号: " << it << '\n';
}
return 0;
}