1、From GossipcaterpillarAlgorithm Gossip: 老鼠走迷官(二)說明由於迷宮的設計,老鼠走迷宮的入口至出口路徑可能不只一條,如何求出所有的路徑呢?解法求所有路徑看起來複雜但其實更簡單,只要在老鼠走至出口時顯示經過的路徑,然後退回上一格重新選擇下一個位置繼續遞迴就可以了,比求出單一路徑還簡單,我們的程式只要作一點修改就可以了。 演算法Procedure GO(maze) VISIT(maze, STARTI, STARTJ);Procedure VISIT(maze, i, j) mazeij = 1; IF(i = ENDI AND j = ENDJ) / FI
2、ND A ROUTE, PRINT THE ROUTEIF(mazeij+1 = 0)VISIT(maze, i, j+1); IF(mazei+1j = 0)VISIT(maze, i+1, j); IF(mazeij-1 = 0)VISIT(maze, i, j-1); if(mazei-1j = 0)VISIT(maze, i-1, j); mazeij = 0; 實作 C #include #include void visit(int, int);int maze99 = 2, 2, 2, 2, 2, 2, 2, 2, 2,2, 0, 0, 0, 0, 0, 0, 0, 2,2, 0
3、, 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+
4、) for(j = 0; j 7; j+) if(mazeij = 2) printf(“); else printf(“ “); printf(“n“); visit(startI, startJ);return 0; void visit(int i, int j) int m, n;mazeij = 1; if(i = endI for(m = 0; m 9; m+) for(n = 0; n 9; n+)if(mazemn = 2)printf(“);else if(mazemn = 1)printf(“);elseprintf(“ “);printf(“n“);if(mazeij+1
5、 = 0) visit(i, j+1);if(mazei+1j = 0) visit(i+1, j);if(mazeij-1 = 0) visit(i, j-1);if(mazei-1j = 0) visit(i-1, j);mazeij = 0; Java public class Mouse private int startI, startJ; / 入口 private int endI, endJ; / 出口public static void main(String args) int maze = 2, 2, 2, 2, 2, 2, 2, 2, 2,2, 0, 0, 0, 0, 0
6、, 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;System.out.println(“顯示迷宮:“); for(int i = 0; i maze.length; i+) for(int j = 0; j maze0.length; j+) if(mazeij
7、= 2) System.out.print(“); else System.out.print(“ “); System.out.println(); Mouse mouse = new Mouse();mouse.setStart(1, 1);mouse.setEnd(7, 7);mouse.go(maze);public void setStart(int i, int j) this.startI = i;this.startJ = j;public void setEnd(int i, int j) this.endI = i;this.endJ = j;public void go(
8、int maze) visit(maze, startI, startJ);private void visit(int maze, int i, int j) mazeij = 1; if(i = endI for(int m = 0; m maze.length; m+) for(int n = 0; n maze0.length; n+) if(mazemn = 2) System.out.print(“); else if(mazemn = 1) System.out.print(“); else System.out.print(“ “); System.out.println();if(mazeij+1 = 0) visit(maze, i, j+1); if(mazei+1j = 0)visit(maze, i+1, j); if(mazeij-1 = 0)visit(maze, i, j-1); if(mazei-1j = 0)visit(maze, i-1, j); mazeij = 0;