4.Algorithm Gossip: 三色棋
说明
三色旗的问题最早由E.W.Dijkstra所提出,他所使用的用语为Dutch Nation Flag(Dijkstra为荷兰人),而多数的作者则使用Three-Color Flag来称之。
假设有一条绳子,上面有红、白、蓝三种颜色的旗子,起初绳子上的旗子颜色并没有顺序,您希望将之分类,并排列为蓝、白、红的顺序,要如何移动次数才会最少,注意您只能在绳子上进行这个动作,而且一次只能调换两个旗子。
解法
在一条绳子上移动,在程序中也就意味只能使用一个阵列,而不使用其它的阵列来作辅助,问题的解法很简单,您可以自己想象一下在移动旗子,从绳子开头进行,遇到蓝色往前移,遇到白色留在中间,遇到红色往后移,如下所示:
只是要让移动次数最少的话,就要有些技巧:
如果图中W所在的位置为白色,则W+1,表示未处理的部份移至至白色群组。
如果W部份为蓝色,则B与W的元素对调,而B与W必须各+1,表示两个群组都多了一个元素。
如果W所在的位置是红色,则将W与R交换,但R要减1,表示未处理的部份减1。
注意B、W、R并不是三色旗的个数,它们只是一个移动的指标;什幺时候移动结束呢?一开始时未处理的R指标会是等于旗子的总数,当R的索引数减至少于W的索引数时,表示接下来的旗子就都是红色了,此时就可以结束移动,如下所示:
C代码如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BLUE 'b' #define WHITE 'w' #define RED 'r' #define SWAP(x, y) { char temp; \ temp = color[x]; \ color[x] = color[y]; \ color[y] = temp; } int main() { char color[] = {'r', 'w', 'b', 'w', 'w', 'b', 'r', 'b', 'w', 'r', '\0'}; int wFlag = 0; int bFlag = 0; int rFlag = strlen(color) - 1; int i; for(i = 0; i < strlen(color); i++) printf("%c ", color[i]); printf("\n"); while(wFlag <= rFlag) { if(color[wFlag] == WHITE) wFlag++; else if(color[wFlag] == BLUE) { SWAP(bFlag, wFlag); bFlag++; wFlag++; } else { while(wFlag < rFlag && color[rFlag] == RED) rFlag--; SWAP(rFlag, wFlag); rFlag--; } } for(i = 0; i < strlen(color); i++) printf("%c ", color[i]); printf("\n"); return 0; }
C++代码:
#include <iostream> #include <string> #include <algorithm> #define BLUE 'B' #define WHITE 'W' #define RED 'R' using namespace std; void adjust(string& sf){ int w=0,b=0,r=sf.size()-1; while(sf[w]==BLUE&&w<sf.size()) { b++; w++; } while(sf[r]==RED&&r>0) r--; while(w<=r){ switch(sf[w]){ case WHITE: w++; break; case BLUE: swap(sf[b],sf[w]); b++; w++; break; case RED: swap(sf[r],sf[w]); r--; break; } } } int main(){ string flags("RWBWWBRBWR"); cout<<flags<<endl; adjust(flags); cout<<flags<<endl; }
5.Algorithm Gossip: 老鼠走迷官(一)
说明
老鼠走迷宫是递回求解的基本题型,我们在二维阵列中使用2表示迷宫墙壁,使用1来表示老鼠的行走路径,试以程序求出由入口至出口的路径。
解法
老鼠的走法有上、左、下、右四个方向,在每前进一格之后就选一个方向前进,无法前进时退回选择下一个可前进方向,如此在阵列中依序测试四个方向,直到走到出口为止,这是递回的基本题,请直接看程序应就可以理解。
#include <stdio.h> #include <stdlib.h> int visit(int, int); int maze[7][7] = {{2, 2, 2, 2, 2, 2, 2}, {2, 0, 0, 0, 0, 0, 2}, {2, 0, 2, 0, 2, 0, 2}, {2, 0, 0, 2, 0, 2, 2}, {2, 2, 0, 2, 0, 2, 2}, {2, 0, 0, 0, 0, 0, 2}, {2, 2, 2, 2, 2, 2, 2}}; int startI = 1, startJ = 1; // 入口 int endI = 5, endJ = 5; // 出口 int success = 0; int main(void) { int i, j; printf("显示迷宫:\n"); for(i = 0; i < 7; i++) { for(j = 0; j < 7; j++) if(maze[i][j] == 2) printf("█"); else printf(" "); printf("\n"); } if(visit(startI, startJ) == 0) printf("\n没有找到出口!\n"); else { printf("\n显示路径:\n"); for(i = 0; i < 7; i++) { for(j = 0; j < 7; j++) { if(maze[i][j] == 2) printf("█"); else if(maze[i][j] == 1) printf("◇"); else printf(" "); } printf("\n"); } } return 0; } int visit(int i, int j) { maze[i][j] = 1; if(i == endI && j == endJ) success = 1; if(success != 1 && maze[i][j+1] == 0) visit(i, j+1); if(success != 1 && maze[i+1][j] == 0) visit(i+1, j); if(success != 1 && maze[i][j-1] == 0) visit(i, j-1); if(success != 1 && maze[i-1][j] == 0) visit(i-1, j); if(success != 1) maze[i][j] = 0; return success; }
6.Algorithm Gossip: 老鼠走迷官(二)
说明
由于迷宫的设计,老鼠走迷宫的入口至出口路径可能不只一条,如何求出所有的路径呢?
解法
求所有路径看起来复杂但其实更简单,只要在老鼠走至出口时显示经过的路径,然后退回上一格重新选择下一个位置继续递回就可以了,比求出单一路径还简单,我们的程序只要作一点修改就可以了。
#include <stdio.h> #include <stdlib.h> void visit(int, int); int maze[9][9] = {{2, 2, 2, 2, 2, 2, 2, 2, 2}, {2, 0, 0, 0, 0, 0, 0, 0, 2}, {2, 0, 2, 2, 0, 2, 2, 0, 2}, {2, 0, 2, 0, 0, 2, 0, 0, 2}, {2, 0, 2, 0, 2, 0, 2, 0, 2}, {2, 0, 0, 0, 0, 0, 2, 0, 2}, {2, 2, 0, 2, 2, 0, 2, 2, 2}, {2, 0, 0, 0, 0, 0, 0, 0, 2}, {2, 2, 2, 2, 2, 2, 2, 2, 2}}; int startI = 1, startJ = 1; // 入口 int endI = 7, endJ = 7; // 出口 int main(void) { int i, j; printf("显示迷宫:\n"); for(i = 0; i < 7; i++) { for(j = 0; j < 7; j++) if(maze[i][j] == 2) printf("█"); else printf(" "); printf("\n"); } visit(startI, startJ); return 0; } void visit(int i, int j) { int m, n; maze[i][j] = 1; if(i == endI && j == endJ) { printf("\n显示路径:\n"); for(m = 0; m < 9; m++) { for(n = 0; n < 9; n++) if(maze[m][n] == 2) printf("█"); else if(maze[m][n] == 1) printf("◇"); else printf(" "); printf("\n"); } } if(maze[i][j+1] == 0) visit(i, j+1); if(maze[i+1][j] == 0) visit(i+1, j); if(maze[i][j-1] == 0) visit(i, j-1); if(maze[i-1][j] == 0) visit(i-1, j); maze[i][j] = 0; }
8.Algorithm Gossip: 八皇后
说明
西洋棋中的皇后可以直线前进,吃掉遇到的所有棋子,如果棋盘上有八个皇后,则这八个皇后如何相安无事的放置在棋盘上,1970年与1971年, E.W.Dijkstra与N.Wirth曾经用这个问题来讲解程序设计之技巧。
解法
关于棋盘的问题,都可以用递回求解,然而如何减少递回的次数?在八个皇后的问题中,不必要所有的格子都检查过,例如若某列检查过,该该列的其它格子就不用再检查了,这个方法称为分支修剪。
所以检查时,先判断是否在已放置皇后的可行进方向上,如果没有再行放置下一个皇后,如此就可大大减少递归的次数,例如以下为修剪过后的递归检查行进路径:
八个皇后的话,会有92个解答,如果考虑棋盘的旋转,则旋转后扣去对称的,会有12组基本解。
#include <stdio.h> #include <stdlib.h> #define N 8 int column[N+1]; // 同栏是否有皇后,1表示有 int rup[2*N+1]; // 右上至左下是否有皇后 int lup[2*N+1]; // 左上至右下是否有皇后 int queen[N+1] = {0}; int num; // 解答编号 void backtrack(int); // 递回求解 int main(void) { int i; num = 0; for(i = 1; i <= N; i++) column[i] = 1; for(i = 1; i <= 2*N; i++) rup[i] = lup[i] = 1; backtrack(1); return 0; } void showAnswer() { int x, y; printf("\n解答 %d\n", ++num); for(y = 1; y <= N; y++) { for(x = 1; x <= N; x++) { if(queen[y] == x) { printf(" Q"); } else { printf(" ."); } } printf("\n"); } } void backtrack(int i) { int j; if(i > N) { showAnswer(); } else { for(j = 1; j <= N; j++) { if(column[j] == 1 && rup[i+j] == 1 && lup[i-j+N] == 1) { queen[i] = j; // 设定为占用 column[j] = rup[i+j] = lup[i-j+N] = 0; backtrack(i+1); column[j] = rup[i+j] = lup[i-j+N] = 1; } } } }
9.Algorithm Gossip: 八枚银币
说明
现有八枚银币a b c d e f g h,已知其中一枚是假币,其重量不同于真币,但不知是较轻或较重,如何使用天平以最少的比较次数,决定出哪枚是假币,并得知假币比真币较轻或较重。
解法
单就求假币的问题是不难,但问题限制使用最少的比较次数,所以我们不能以单纯的回圈比较来求解,我们可以使用决策树(decision tree),使用分析与树状图来协助求解。一个简单的状况是这样的,我们比较a+b+c与d+e+f ,如果相等,则假币必是g或h,我们先比较g或h哪个较重,如果g较重,再与a比较(a是真币),如果g等于a,则g为真币,则h为假币,由于h比g轻而 g是真币,则h假币的重量比真币轻。
#include <stdio.h> #include <stdlib.h> #include <time.h> void compare(int[], int, int, int); void eightcoins(int[]); int main(void) { int coins[8] = {0}; int i; srand(time(NULL)); for(i = 0; i < 8; i++) coins[i] = 10; printf("\n输入假币重量(比10大或小):"); scanf("%d", &i); coins[rand() % 8] = i; eightcoins(coins); printf("\n\n列出所有钱币重量:"); for(i = 0; i < 8; i++) printf("%d ", coins[i]); printf("\n"); return 0; } void compare(int coins[], int i, int j, int k) { if(coins[i] > coins[k]) printf("\n假币 %d 较重", i+1); else printf("\n假币 %d 较轻", j+1); } void eightcoins(int coins[]) { if(coins[0]+coins[1]+coins[2] == coins[3]+coins[4]+coins[5]) { if(coins[6] > coins[7]) compare(coins, 6, 7, 0); else compare(coins, 7, 6, 0); } else if(coins[0]+coins[1]+coins[2] > coins[3]+coins[4]+coins[5]) { if(coins[0]+coins[3] == coins[1]+coins[4]) compare(coins, 2, 5, 0); else if(coins[0]+coins[3] > coins[1]+coins[4]) compare(coins, 0, 4, 1); if(coins[0]+coins[3] < coins[1]+coins[4]) compare(coins, 1, 3, 0); } else if(coins[0]+coins[1]+coins[2] < coins[3]+coins[4]+coins[5]) { if(coins[0]+coins[3] == coins[1]+coins[4]) compare(coins, 5, 2, 0); else if(coins[0]+coins[3] > coins[1]+coins[4]) compare(coins, 3, 1, 0); if(coins[0]+coins[3] < coins[1]+coins[4]) compare(coins, 4, 0, 1); } }
12.Algorithm Gossip: 双色、三色河内塔
说明
双色河内塔与三色河内塔是由之前所介绍过的河内塔规则衍生而来,双色河内塔的目的是将下图左上的圆环位置经移动成为右下的圆环位置:
而三色河内塔则是将下图左上的圆环经移动成为右上的圆环:
解法
无论是双色河内塔或是三色河内塔,其解法观念与之前介绍过的河内塔是类似的,同样也是使用递回来解,不过这次递回解法的目的不同,我们先来看只有两个盘的情况,这很简单,只要将第一柱的黄色移动至第二柱,而接下来第一柱的蓝色移动至第三柱。
再来是四个盘的情况,首先必须用递回完成下图左上至右下的移动:
接下来最底层的就不用管它们了,因为它们已经就定位,只要再处理第一柱的上面两个盘子就可以了。那么六个盘的情况呢?一样!首先必须用递回完成下图左上至右下的移动:
接下来最底层的就不用管它们了,因为它们已经就定位,只要再处理第一柱上面的四个盘子就可以了,这又与之前只有四盘的情况相同,接下来您就知道该如何进行解题了,无论是八个盘、十个盘以上等,都是用这个观念来解题。
那么三色河内塔呢?一样,直接来看九个盘的情况,首先必须完成下图的移动结果:
接下来最底两层的就不用管它们了,因为它们已经就定位,只要再处理第一柱上面的三个盘子就可以了。
双色河内塔 C 实作
#include <stdio.h> void hanoi(int disks, char source, char temp, char target) { if (disks == 1) { printf("move disk from %c to %c\n", source, target); printf("move disk from %c to %c\n", source, target); } else { hanoi(disks-1, source, target, temp); hanoi(1, source, temp, target); hanoi(disks-1, temp, source, target); } } void hanoi2colors(int disks) { char source = 'A'; char temp = 'B'; char target = 'C'; int i; for(i = disks / 2; i > 1; i--) { hanoi(i-1, source, temp, target); printf("move disk from %c to %c\n", source, temp); printf("move disk from %c to %c\n", source, temp); hanoi(i-1, target, temp, source); printf("move disk from %c to %c\n", temp, target); } printf("move disk from %c to %c\n", source, temp); printf("move disk from %c to %c\n", source, target); } int main() { int n; printf("请输入盘数:"); scanf("%d", &n); hanoi2colors(n); return 0; }
三色河内塔 C 实作
#include <stdio.h> void hanoi(int disks, char source, char temp, char target) { if (disks == 1) { printf("move disk from %c to %c\n", source, target); printf("move disk from %c to %c\n", source, target); printf("move disk from %c to %c\n", source, target); } else { hanoi(disks-1, source, target, temp); hanoi(1, source, temp, target); hanoi(disks-1, temp, source, target); } } void hanoi3colors(int disks) { char source = 'A'; char temp = 'B'; char target = 'C'; int i; if(disks == 3) { printf("move disk from %c to %c\n", source, temp); printf("move disk from %c to %c\n", source, temp); printf("move disk from %c to %c\n", source, target); printf("move disk from %c to %c\n", temp, target); printf("move disk from %c to %c\n", temp, source); printf("move disk from %c to %c\n", target, temp);; } else { hanoi(disks/3-1, source, temp, target); printf("move disk from %c to %c\n", source, temp); printf("move disk from %c to %c\n", source, temp); printf("move disk from %c to %c\n", source, temp); hanoi(disks/3-1, target, temp, source); printf("move disk from %c to %c\n", temp, target); printf("move disk from %c to %c\n", temp, target); printf("move disk from %c to %c\n", temp, target); hanoi(disks/3-1, source, target, temp); printf("move disk from %c to %c\n", target, source); printf("move disk from %c to %c\n", target, source); hanoi(disks/3-1, temp, source, target); printf("move disk from %c to %c\n", source, temp); for (i = disks / 3 - 1; i > 0; i--) { if (i>1) { hanoi(i-1, target, source, temp); } printf("move disk from %c to %c\n",target, source); printf("move disk from %c to %c\n",target, source); if (i>1) { hanoi(i-1, temp, source, target); } printf("move disk from %c to %c\n", source, temp); } } } int main() { int n; printf("请输入盘数:"); scanf("%d", &n); hanoi3colors(n); return 0; }