1. 程式人生 > >{GIS演算法}地圖四色著圖/C語言程式碼/演算法

{GIS演算法}地圖四色著圖/C語言程式碼/演算法

四色原理是什麼?網上原理有很多,不懂可以自己搜。 把需要填圖的區域看作泰森多邊形,每個區域的頂點儲存顏色,點之間關係就是TIN三角形,區域和區域的關係就轉化為點和點之間的關係。 把所有點儲存在鄰接表裡,著色採用回溯法,原理就是圖的遍歷。 不懂可以複製下來自己執行一下。

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTEX_NUM 20


typedef struct ArcNode {
    int
adjvex; struct ArcNode *nextarc; } ArcNode; typedef struct { float x; float y; } Vertex; typedef struct VNode { Vertex data; ArcNode *firstarc; int color; } VNode; typedef struct{ VNode vertics[MAX_VERTEX_NUM]; int vexnum, arcnum; } UDGraph; bool isColorOK(UDGraph, int
); bool getColorPowset(UDGraph &, int, int); int createUDGraph(UDGraph &); void outputGraph(UDGraph); bool isColorOK(UDGraph G, int node) { VNode V = G.vertics[node - 1]; ArcNode *T = V.firstarc; while(T) { if(V.color == G.vertics[T->adjvex].color) return
false; T = T->nextarc; } return true; } bool getColorPowset(UDGraph &G, int color_Num, int step) { if(step > G.vexnum) return true; else { int i; for(i=1; i<=color_Num; i++) { G.vertics[step - 1].color = i; if(isColorOK(G, step)) if(getColorPowset(G, color_Num, step + 1)) return true; G.vertics[step - 1].color = 0; } } return false; } int createUDGraph(UDGraph &G) { int a, b, i; ArcNode *p; printf("請輸入結點的個數和邊的個數:"); scanf("%d,%d", &(G.vexnum), &(G.arcnum)); getchar(); for(i=0; i<G.vexnum; i++) { G.vertics[i].firstarc =NULL; G.vertics[i].color = 0; } printf("請輸入這%d個點之間的拓撲關係:\n", G.vexnum); for(i=1; i<=G.arcnum; i++) { scanf("%d,%d", &a, &b); getchar(); p = (ArcNode*)malloc(sizeof(ArcNode)); if(!p) exit(-2); p->adjvex = b - 1; p->nextarc = G.vertics[a - 1].firstarc; G.vertics[a - 1].firstarc = p; p = (ArcNode*)malloc(sizeof(ArcNode)); if(!p) exit(-2); p->adjvex = a - 1; p->nextarc = G.vertics[b - 1].firstarc; G.vertics[b - 1].firstarc = p; } return 1; } void outputGraph(UDGraph G) { int i; for(i=0; i<G.vexnum; i++) printf("結點%d的著色方案為:%d\n", i+1, G.vertics[i].color); } int main() { UDGraph G; createUDGraph(G); if(getColorPowset(G, 4, 1)) { printf("圖形圖色成功,為:\n"); outputGraph(G); } else printf("圖形圖色失敗\n"); return 1; }