地圖四著色問題

來源:互聯網
上載者:User

標籤:地圖   四著色   

一、介紹

    對地圖的著色問題,能否用四個顏色對地圖著色,要求每個相鄰的地區都要著上不同的顏色。


二、演算法思路

例如中國的省份為例,從一個省開始,給它塗上任意一種顏色1,遍曆它旁邊的省份,塗上與已經塗色並於他相鄰的省份不同的顏色就行了。

遞迴求解;在前面的n-1個節點都合法的著色之後,開始對第n個節點著色。這時候枚舉可用的4個顏色(4著色),通過和與它相鄰的節點的顏色相比較,來判斷這個顏色是否合法。找到一種顏色能使第n個節點合法著色即可完成中國地圖4著色。


三、代碼

#include <stdio.h>//N=number of city + 1#define N 8int isOk(int metrix[N][N],int city[N],int current){    for(int j=0; j<current; j++)        if(metrix[current][j]==1&&city[j]==city[current])            return 0;    return 1;}void color(int metrix[N][N],int city[N],int sum,int current){    if(current<=sum)        for(int i=1; i<=4; i++)     //colored current city        {            city[current]=i;            if(isOk(metrix,city,current))            {                color(metrix,city,sum,current+1);   //colored next city                break;            }        }}int main(){    int city[N]= {0};    int metrix[N][N]=  {                        {0,1,1,0,0,0,0},                        {1,0,0,1,0,1,0},                        {1,0,0,1,1,0,0},                        {0,1,1,0,1,1,0},                        {0,0,1,1,0,1,1},                        {0,1,0,1,1,0,1},                        {0,0,0,0,1,1,0}                       };    printf("總共有%d個城市\n",N-1);    color(metrix,city,N-1,0);    printf("\n著色方法:\n");    for(int i=0; i<N-1; i++)        printf("%3d",city[i]);    return 0;}


四、總結

    這個代碼有點簡單,因為是事先輸入了城市之間的關係。如果從實際角度考慮,應該要手動收入然後輸出。最好還能夠用圖形化介面顯示著色情況。

地圖四著色問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.