回溯 / 遞歸
首先判斷傳入的顏色是否為最后的顏色’d’,如果是說明至少還得向上回溯一次。
如果一切正常不是’d’的話,那就開始填色。
遍歷與之相鄰的是否重色,如果重色 則本區域取下一色,直到遞歸傳入’d’為之
如果不重色就從第一個顏色開始試探下一區域。
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 5 struct region { 6 int id; 7 region* next; 8 region* last; 9 }r1,r2,r3,r4,r5,r6,r7; 10 11 int a[7][7] = { {0,1,1,1,1,1,0},{1,0,0,0,0,1,0},{1,0,0,1,1,0,0},{1,0,1,0,1,1,0},{1,0,1,1,0,1,0},{1,1,0,1,1,0,0},{0,0,0,0,0,0,0} }; 12 13 int fill(region currentRegion,int currentColor,int a[7][7],int* result ) { 14 //先判斷傳入顏色是否是d,如果是的話說明還要向上回溯 15 if (currentColor <'d') 16 { 17 result[currentRegion.id - 1] = ++currentColor; 18 //判斷是否重色 19 bool isrepeat = false; 20 int temp; 21 for (int i = 0; i < 7; i++) { 22 if (a[currentRegion.id - 1][i] == 1) { 23 if (currentColor == result[i]) { 24 temp = i; 25 isrepeat = true; 26 break; 27 } 28 } 29 30 } 31 if (isrepeat) { 32 //先判斷是否需要回溯 33 cout << currentRegion.id << "is repeat with" << temp + 1 << "," << currentColor << endl; 34 if (currentColor == 'd') { 35 int rullbackNumber = result[currentRegion.id - 2] + 1; 36 result[currentRegion.id - 1] = 0; 37 currentRegion = *currentRegion.last; 38 fill(currentRegion, rullbackNumber, a, result); 39 } 40 else { 41 //如果重復,填下一個顏色 42 43 fill(currentRegion, currentColor, a, result); 44 } 45 46 } 47 else { 48 if (currentRegion.next) 49 fill(*currentRegion.next, 96, a, result); 50 else 51 return 0; 52 } 53 } 54 else { 55 int rullbackNumber = result[currentRegion.id - 2] + 1; 56 result[currentRegion.id - 1] = 0; 57 currentRegion = *currentRegion.last; 58 fill(currentRegion, rullbackNumber, a, result); 59 } 60 61 } 62 63 void dispArr(int* arr, int n) 64 { 65 for (int i = 0; i < n; i++) 66 { 67 char temp = arr[i]; 68 cout << "arr" << "[" << i +1<< "]" << " is:" << temp << endl; 69 } 70 } 71 72 73 74 int main() { 75 r1.id = 1; 76 r2.id = 2; 77 r3.id = 3; 78 r4.id = 4; 79 r5.id = 5; 80 r6.id = 6; 81 r7.id = 7; 82 r1.last = nullptr; 83 r1.next = &r2; 84 r2.last = &r1; 85 r2.next = &r3; 86 r3.last = &r2; 87 r3.next = &r4; 88 r4.last = &r3; 89 r4.next = &r5; 90 r5.last = &r4; 91 r5.next = &r6; 92 r6.last = &r5; 93 r6.next = &r7; 94 r7.last = &r6; 95 r7.next = nullptr; 96 97 int* result = new int[7]{0,0,0,0,0,0,0}; 98 99 int x=fill(r1,96,a,result); 100 dispArr(result, 7); 101 102 delete result; 103 }
感謝,https://www.cnblogs.com/walter-xh/p/6192800.html