老鼠走迷官(一)

說明

老鼠走迷宮是遞迴求解的基本題型,我們在二維陣列中使用2表示迷宮牆壁,使用1來表示老鼠的行走路徑,試以程式求出由入口至出口的路徑。

解法

老鼠的走法有上、左、下、右四個方向,在每前進一格之後就選一個方向前進,無法前進時退回選擇下一個可前進方向,如此在陣列中依序測試四個方向,直到走到出口為止,這是遞迴的基本題,請直接看程式應就可以理解。 

演算法

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"); 
    }     
}

你可能感兴趣的:(老鼠走迷官(一))