今天笔试的一道题,在网上搜到的答案。

本文介绍了一种解决地图四色问题的算法实现,通过递归与循环的嵌套方式,对地图上的每个区域进行有效的颜色分配,确保相邻区域颜色不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

地图4色算法

 

 #include<stdio.h>

#define  N 10

void output(int color[])/*输出一种着色方案*/

{ int i ;

    for ( i = 0 ; i < N ; i++ )

        printf( "%4d" , color[i] ) ;

    printf( "/n" ) ;

}

int back( int *ip ,int color[] ) /*回溯*/

{
        int c = 4 ;

    while ( c == 4 )
        {

        if ( *ip <= 0 )
                        return 0 ;

        --(*ip) ;

        c = color[*ip];

        color[*ip] = -1 ;

    }

    return c ;

}

/*检查区域i,对c种颜色的可用性*/

int colorok( int i , int c , int adj[][N] , int color[ ] )

{
        int j ;

    for ( j = 0 ; j < i ; j++ )

        if (adj[i][j] != 0 && color[j] == c)

            return 0 ;

    return 1 ;

}
/*为区域i选一种可着的颜色*/

int select( int i ,int c ,int adj[][N] , int color[ ] )

{ int k ;

    for ( k = c ; k <= 4 ; k++ )

        if ( colorok(i,k,adj,color) )

            return k ;

        return 0 ;

}

int coloring( int adj[][N] ) /*寻找各种着色方案*/

{
        int color[N] , i , c , cnt ;

    for ( i = 0 ; i < N ; i++ )
                color[i] = -1 ;

    i = c = 0 ;
        cnt = 0 ;

    while ( 1 ) {

        if ( ( c =select (i,c+1,adj,color) ) == 0 ){

            c = back( &i , color) ;

            if ( c == 0) return cnt ;

        }
                else
               
                {
                        color[i]=c; i++ ;

            if ( i == N ) {

                    output(color) ;

                    ++cnt ;

                    c = back( &i , color ) ;

                  }
                        else
                                c = 0 ;

                }

        }

}

void main()

{
        int adj[N][N] =  { {0,1,0,1,1,1,1,1,1,1},
        {1,0,1,1,0,1,1,1,1,0},
        {0,1,0,1,0,1,1,0,1,1},
        {1,1,1,0,1,1,0,0,1,1},
        {1,0,0,1,0,1,0,0,0,0},
        {1,1,1,1,1,0,1,0,0,1},
        {1,1,1,0,0,1,0,0,1,0},
        {1,1,0,0,0,0,0,0,1,1},
        {1,1,1,1,0,0,1,1,0,1},
        {1,0,1,1,0,1,0,1,1,0}} ;

    printf( "共有%d组解./n",coloring( adj ) ) ;coloring( adj ) ;

}

 

 

这是一个递归与循环的嵌套。
用循环对每一个地图格的周围三个格子进行搜索。
(周围共四个格子,其中一个是初始格)
对于每一次搜索,再用递归进行下一层的搜索。
这样循环并递归下去,就能对整幅地图充分搜索了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值