当前位置:甜馍馍地理信息网 >> 地理信息系统GIS >> 算法与数据结构 >> 正文 >>  [阅读资讯:地图着色算法原理及C语言实现实例]

地图着色算法原理及C语言实现实例

[ 来源:GIS帝国 | 时间:2007年10月09日 | 收藏本文 ] 【

昨天,一朋友打电话询问我如何给地图着色?给地图着色的原理和算法是什么?后来我研究了一下,将结果告诉大家,并用C语言写了一个小的地图着色例子.

定理:任何平面地图可以使用4种颜色给每个不同的城市着色,而保证相邻的城市着不同的颜色。


思路:把地图上的每个城市抽象为一个点,并给每个城市编号,相邻的城市之间用直线连接。据此做出邻接矩阵,若第i个城市与第j个城市相邻,则metro[i][j]=1,否则metro[i][j]=0。


算法:按照编号从小到大的顺序检查每个城市,对每个城市从1到4使用4种颜色着色,若当前颜色可用(即不与相邻城市颜色相同),则着色;否则测试下一种颜色。

程序:
#i nclude <stdio.h>
#define N 21

int ok(int metro[N][N],int r_color[N],int current)
{/*测试当前着色方案是否可行*/
   int j;
   for(j=1;j<current;j++)
     if(metro[current][j]==1&&r_color[j]==r_color[current])
          return 0;/*城市相邻且颜色相同*/
   return 1;
}

void go(int metro[N][N],int r_color[N],int sum,int current)
{
   int i;
   if(current<=sum)/*检查所有城市*/
      for(i=1;i<=4;i++)/*测试每种颜色*/
      {
            r_color[current]=i;/*尝试着色*/
            if(ok(metro,r_color,current))/*若尝试成功*/
           {
                 go(metro,r_color,sum,current+1);/*检查下一个城市*/
                 return;
          }
      }
}

void main()
{
   int r_color[N]={0};
   int i;
   int metro[N][N]={{0},/*邻接矩阵*/
                            {0,1,1,1,1,1,1},
                            {0,1,1,1,1},
                            {0,1,1,1,0,0,1},
                            {0,1,1,0,1,1},
                            {0,1,0,0,1,1,1,0,0,1,0,0,0,0,0,0,1},
                            {0,1,0,1,0,1,1,1,1,1},
                            {0,0,0,0,0,0,1,1,1},
                            {0,0,0,0,0,0,1,1,1,1,0,0,1},
                            {0,0,0,0,0,1,1,0,1,1,0,0,1,1,1,0,1},
                            {0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,1,0,0,0,1},
                            {0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,1},
                            {0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0,0,0,1,1},
                            {0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1},
                            {0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,1},
                            {0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,1,1,0,1},
                            {0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,1,1},
                            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1},
                            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1},
                            {0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,0,0,1,1,1},
                            {0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1}};
   go(metro,r_color,20,1);
   printf("\n");
   for(i=1;i<=20;i++)/*输出着色方案*/
     printf("%3d",r_color[i]);
}

想了一下,把上面程序中的go函数和ok函数合并一下,并且不使用递归,于是写下了下面color函数的代码,main函数不变,但调用方式变为color(metro,r_color,20);请朋友多批评

void color(int metro[N][N],int r_color[N],int sum)
{
   int i,j,k;
   for(i=1;i<=sum;i++)/*检查所有城市*/
     for(j=1;j<=4;j++)/*对每个城市尝试4种颜色的着色方案*/
     {
        r_color[i]=j;/*尝试着色*/
        for(k=1;k<i;k++)/*检查是否与相邻城市颜色相同*/
            if(metro[i][k]==1&&r_color[k]==r_color[i])
               break;/*相同则跳出,此时有k<i,则下面条件不成立,继续尝试下一种颜色*/
        if(k>=i)/*若不相同,则使用当前颜色,并检查下一个城市*/
            break;
     }
}

【推荐本文】 【打印本页】 【返回顶部
最新文章
推荐文章