【Wikioi】1116四色问题

来源:互联网 发布:python 条码 编辑:程序博客网 时间:2024/06/02 09:03

用邻接矩阵表示图。

DFS回溯。

每次搜索当前点之前的点,如果相邻且颜色有重复,则换一种颜色。

这里dfs回溯的时候,回溯到i之前的点,那么history[i]是什么颜色就无所谓了,所以标记不需要还原。

#include <stdio.h>#include <string.h>#define MAXN 8int N;int g[MAXN][MAXN];int history[MAXN];int count;void dfs2(int i){    if (i == N)    {        count++;    }    else for (int color = 1; color < 5; color++)    {         bool ok=true;         for(int j=0;j<i;j++)         {             if(g[i][j]==1 && history[j]==color)              {                  ok=false;                  break;              }         }         if(ok)         {             history[i]=color;             dfs2(i+1);             history[i]=0;         }    }}int main(){    int i, j;    N=4;    for (i = 0; i < N; i++)    {        for (j = 0; j < N; j++)        {            g[i][j]=0;        }    }    g[0][1]=1;g[1][0]=1;g[1][3]=1;g[3][1]=1;    dfs2(0);//144    printf("%d\n", count);    return 0;}


0 0
原创粉丝点击