测试环境:vs2013
Maze.h
#pragma once
#define MAX_ROW 4
#define MAX_COL 4
typedef struct Position
{
int _x;
int _y;
}Position;
typedef struct Maze
{
int _map[MAX_ROW][MAX_COL];
}Maze, *PMaze;
void InitMaze(PMaze pm, int map[][MAX_COL]);
int IsValidEntry(PMaze pm, Position entry);
int IsPass(PMaze pm, Position cur);
int IsExit(PMaze pm, Position cur, Position entry);
int _PassMaze(PMaze pm, Position entry, Position cur, PStack ps);
void PassMaze(PMaze pm, Position entry, PStack ps);
void PrintMaze(PMaze pm, int map[][MAX_COL]);
Maze.c
#include "stack.h"
#include "Maze.h"
void PrintMaze(PMaze pm)
{
int i = 0;
assert(pm);
for (; i < MAX_ROW; ++i)
{
int j = 0;
for (; j < MAX_COL; ++j)
{
printf("%d ", pm->_map[i][j]);
}
printf("\n");
}
}
void InitMaze(PMaze pm, int map[][MAX_COL])
{
int i = 0;
assert(pm);
for (; i < MAX_ROW; ++i)
{
int j = 0;
for (; j < MAX_COL; ++j)
{
pm->_map[i][j] = map[i][j];
}
}
}
int IsValidEntry(PMaze pm, Position entry)
{
assert(pm);
if ((entry._x == 0 || entry._y == 0 || entry._x == MAX_ROW - 1
|| entry._y == MAX_COL - 1) && (pm->_map[entry._x][entry._y] == 1))
return 1;
return 0;
}
int IsPass(PMaze pm, Position cur)
{
assert(pm);
if ((cur._x >= 0 && cur._x <= MAX_ROW - 1) &&
(cur._y >= 0 && cur._y <= MAX_COL - 1) &&
pm->_map[cur._x][cur._y] == 1)
return 1;
return 0;
}
int IsExit(PMaze pm, Position cur, Position entry)
{
assert(pm);
if ((cur._x == 0 || cur._y == 0 || cur._x == MAX_ROW - 1
|| cur._y == MAX_COL - 1) && (pm->_map[cur._x][cur._y] == 1)
&& ((cur._x != entry._x) || (cur._y != entry._y)))
return 1;
return 0;
}
int _PassMaze(PMaze pm, Position entry, Position cur, PStack ps)
{
Position next;
assert(pm);
assert(ps);
if (IsPass(pm, cur))
{
StackPush(ps, cur);
if (IsExit(pm, cur, entry))
{
pm->_map[cur._x][cur._y] = 2;
return 1;
}
pm->_map[cur._x][cur._y] = 2;
next = cur;
next._x -= 1;
if (_PassMaze(pm, entry, next, ps))
return 1;
next = cur;
next._y -= 1;
if (_PassMaze(pm, entry, next, ps))
return 1;
next = cur;
next._y += 1;
if (_PassMaze(pm, entry, next, ps))
return 1;
next = cur;
next._x += 1;
if (_PassMaze(pm, entry, next, ps))
return 1;
pm->_map[cur._x][cur._y] = 3;
StackPop(ps);
}
return 0;
}
void PassMaze(PMaze pm, Position entry, PStack ps)
{
assert(pm);
assert(ps);
if (!IsValidEntry(pm, entry))
{
printf("迷宫入口不合法!!!\n");
return;
}
_PassMaze(pm, entry, entry, ps);
}
test.c
#include "stack.h"
#include "Maze.h"
#include <windows.h>
Position entry;
Maze m;
PMaze pm = &m;
StackInit(ps, 10);
int map[4][4] = { { 0, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 0 }};
InitMaze(pm, map);
PrintMaze(pm, map);
entry._x = 3;
entry._y = 1;
PassMaze(pm, entry, ps);
PrintMaze(pm, map);
}
int main()
{
Stack s;
PStack ps = &s;
TestMaze(ps);
system("pause");
return 0;
}
在递归过程中函数的栈帧结构大致如下: