数据结构书上的。。。
依旧回溯
#include <iostream> #include <string.h> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int num; // 区域数量 int arr[100][100]; // 区域颜色邻接矩阵 int stack[100]; // 数组模拟栈 int top = -1; // 指针 bool canuse(int area, int color) { int i = 0; do { if(arr[area][i] == 1 && stack[i] == color) return false; i++; } while(i <= top); return true; } // 地图四染色 int main(int argc, char *argv[]) { cin>>num; memset(arr, 0, sizeof(int) * 10000); // 输入邻接矩阵,(深入理解计算机系统162页,且这样试试吧) int *row = &arr[0][0]; int j = 0; do { int i = 0; do { cin>>row[i]; i++; }while(i < num); row += 100; j++; }while(j < num); // 回溯求解 int trying = 0; do { while( top < num - 1 && canuse(top + 1, trying) && trying < 4) { top++; stack[top] = trying; trying = 0; } if(top == num - 1) { for(int i = 0 ; i < num; i++) { cout<<stack[i]<<" "; } cout<<endl; trying = stack[top] + 1; top--; } else if( trying >= 4) { trying = stack[top] + 1; top--; } else { trying++; } }while(top != -1 || trying != 4); return 0; }
此博客主要是个人记录