《回溯算法的趣例》
DFS是深度优先搜索算法,通过这种方式能够很轻松的解决四色问题。PS:这个题是当时年少无知的时候写的,我甚至不确定当时自己知不知道什么是DFS,哈哈,也不知道为什么会整理这样一道题,现在看来这个题感觉还挺有意思的,就是典型的回溯算法,和解决八皇后的问题如出一辙。比较有技巧的地方是,我们需要根据给定的图例勾画一个矩阵。
Key Words:四色问题、DFS
Beijing, 2020
作者:RaySue
Description:
每个区域代表一个省,区域中的数字代表省的编号,今将每个省涂上红(R),蓝(B),黄(Y),绿(W)四种颜色之一,使相邻的省份不同颜色,如果区域1只 涂红色,那么总共有多少不同的涂法?
Solution:
首先用一个矩阵来表示区域的相邻情况,矩阵的每一行表示一个地区和所有地区的相邻情况,如果两个地区相邻,那么为1,反之为0。对于上图而言,相邻矩阵为:
1 2 3 4 5 6 7
1 {{0, 1, 0, 0, 0, 0, 1},
2 { 1, 0, 1, 1, 1, 1, 1},
3 { 0, 1, 0, 1, 0, 0, 0},
4 { 0, 1, 1, 0, 1, 0, 0},
5 { 0, 1, 0, 1, 0, 1, 0},
6 { 0, 1, 0, 0, 1, 0, 1},
7 { 1, 1, 0, 0, 0, 1, 0}};
求解思路为:第一个地区的颜色是固定的,所以第二个地区开始遍历颜色,如果和第一个地区相邻的颜色相同,则换下一个颜色,如果不同,那么第三个地区开始遍历颜色,进行深度的递归。
对所有的地区都遍历所有的颜色,并保留满足需求的配色方案,返回。
#include<cstdio>
using namespace std;
int n = 7;
int regions[7]; // 初始化地区
int total = 0;
// 初始化地区间的关系 1表示相邻,0表示不相邻
int connection[7][7] = {{0, 1, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 1, 1},
{0, 1, 0, 1, 0, 0, 0},
{0, 1, 1, 0, 1, 0, 0},
{0, 1, 0, 1, 0, 1, 0},
{0, 1, 0, 0, 1, 0, 1},
{1, 1, 0, 0, 0, 1, 0}};
// 剪枝 判断当前的颜色是否与相邻的冲突
bool is_different_color_with_neighbor(int depth, int color)
{
for (int j = 0; j < depth; j++)
{
if (connection[depth][j] == 1)
{
if (color == regions[j])
{
return false;
}
}
}
return true;
}
void backtrack(int depth)
{
if (depth == n) // dep -> current region
{
for (int i = 0; i < n; i++) printf("%d ", regions[i]);
printf("\n");
total++;
return;
}
for (int color = 1; color <= 4; color++)
{
// depth 指定了第几个地区
if (!is_different_color_with_neighbor(depth, color)) continue;
regions[depth] = color;
backtrack(depth + 1); // if different color -> next region
regions[depth] = 0; // [region] same color -> next color
}
}
int main()
{
// 区域 1 只用红色
regions[0] = 1;
// First region's color was fixed, so enumerate colors from second region
DFS(1);
printf("Number of all strategies: %d", total);
return 0;
}