Procedure GO(maze[]) [ VISIT(maze, STARTI, STARTJ); ] Procedure VISIT(maze[], i, j) [ maze[i][j] = 1; IF(i == ENDI AND j == ENDJ) success = TRUE; IF(success != TRUE AND maze[i][j+1] == 0) VISIT(maze, i, j+1); IF(success != TRUE AND maze[i+1][j] == 0) VISIT(maze, i+1, j); IF(success != TRUE AND maze[i][j-1] == 0) VISIT(maze, i, j-1); if(success != TRUE AND maze[i-1][j] == 0) VISIT(maze, i-1, j); IF(success != TRUE) maze[i][j] = 0; ]
實作:
#include <stdio.h> #include <stdlib.h> #define SIZE 7 #define START_I 1 #define START_J 1 #define END_I 5 #define END_J 5 int visit(int maze[][SIZE], int, int); int isArrived(int maze[][SIZE], int, int); void printMaze(int maze[][SIZE]); int main(void) { int maze[SIZE][SIZE] = {{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}}; if(visit(maze, START_I, START_J) == 0) printf("\n沒有找到出口!\n"); printMaze(maze); return 0; } int visit(int maze[][SIZE], int i, int j) { maze[i][j] = 1; if(!isArrived(maze, i, j) && maze[i][j+1] == 0) visit(maze, i, j+1); if(!isArrived(maze, i, j) && maze[i+1][j] == 0) visit(maze, i+1, j); if(!isArrived(maze, i, j) && maze[i][j-1] == 0) visit(maze, i, j-1); if(!isArrived(maze, i, j) && maze[i-1][j] == 0) visit(maze, i-1, j); if(!isArrived(maze, i, j)) maze[i][j] = 0; return isArrived(maze, i, j); } int isArrived(int maze[][SIZE], int i, int j) { return maze[END_I][END_J]; } void printMaze(int maze[][SIZE]) { int i, j; for(i = 0; i < SIZE; i++) { for(j = 0; j < SIZE; j++) { if(maze[i][j] == 2) printf("█"); else if(maze[i][j] == 1) printf("◇"); else printf(" "); } printf("\n"); } }