一道C语言面试题——迷宫的回溯算法

#include "stdafx.h"
#define MAX_SIZE  8

int H[4] = {0, 1, 0, -1};            //水平方向下一位置相对当前位置的距离
int V[4] = {-1, 0, 1, 0};            //垂直方向下一位置相对当前位置的距离

//迷宫:o-通路,X-障碍(可以不是方阵)
char Maze[MAX_SIZE][MAX_SIZE] = {   {'X','X','X','X','X','X','X','X'},
                                    {'o','o','o','o','o','X','X','X'},
                                    {'X','o','X','X','o','o','o','X'},
                                    {'X','o','X','X','o','X','X','o'},
                                    {'X','o','X','X','X','X','X','X'},
                                    {'X','o','X','X','o','o','o','X'},
                                    {'X','o','o','o','o','X','o','o'},
                                    {'X','X','X','X','X','X','X','X'}
                                };

// 寻找通路函数
void FindPath(int X, int Y)   
{
    if(X == MAX_SIZE || Y == MAX_SIZE)
    {
       for(int i = 0; i < MAX_SIZE; i++)          // 到达出口,输出被标记通路的迷宫
           for(int j = 0; j < MAX_SIZE; j++)
               printf("%c%c", Maze[i][j], j < MAX_SIZE-1 ? ' ' : '/n');
    }else for(int k = 0; k < 4; k++)               // 未到出口时,从四个方向继续寻找
               if(X >= 0 && Y >= 0 && Y < MAX_SIZE && X < MAX_SIZE && 'o' == Maze[X][Y])
                {
                   Maze[X][Y] = ' ';
                   FindPath(X+V[k], Y+H[k]);
                   Maze[X][Y] = 'o';              // 找到出口或此路不通时回溯
                }
}

int main(int argc, char* argv[])
{
    FindPath(1,0);
    return getchar();
}

你可能感兴趣的:(面试,算法,语言,c,include)