迷宫问题

/*
*电子老鼠闯迷宫
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_SIZE 101 //最大迷宫不超过100*100
#define FALSE 0
#define TRUE 1

static int maze[MAX_SIZE][MAX_SIZE]; //迷宫矩阵
static int mark[MAX_SIZE][MAX_SIZE]; //标记矩阵

/*构造栈*/
typedef struct{
short int row;
short int col;
short int dir;
} element;
//
typedef struct{
short int vert;
short int horiz;
} offset;
//
static offset move[8] = {
{-1, 0}, {-1, 1}, {0, 1}, {1, 1},
{1, 0}, {1, -1}, {0, -1}, {-1, -1}
};
static element stack[MAX_SIZE*MAX_SIZE];
static int top = -1;
//
void push(element item)
{
if(top >= MAX_SIZE*MAX_SIZE-1)
{
printf("The stack is full\n");
exit(EXIT_FAILURE);
}
stack[++top] = item;
}
//
element pop(void)
{
if(top < 0)
{
printf("The stack is empty\n");
exit(EXIT_FAILURE);
}
return stack[top--];
}

/*输入参数为迷宫行数、列数,输出rows*cols迷宫矩阵*/
void makeMaze(int rows, int cols)
{
int i, j;
srand(time(0));
for(j = 0; j <= cols+1; j++)
maze[0][j] = 1;
for(i = 1; i <= rows+1; i++)
maze[i][cols+1] = 1;
for(j = cols; j >= 0; j--)
maze[rows+1][j] = 1;
for(i = rows; i > 0; i--)
maze[i][0] = 1;
for(i = 1; i <= rows; i++){
for(j = 1; j <= cols; j++){
if(i == 1 && j == 1) // entry
maze[i][j] = 0;
else if(i == rows && j == cols)
maze[i][j] = 0; // exit
else
maze[i][j] = rand()%2;
}
}
}
//
void path(int exitRow, int exitCol)
{
int i, row, col, nextRow, nextCol, dir, found = FALSE;
element pos;
mark[1][1] = 1;
top = 0;
stack[0].row = 1;
stack[0].col = 1;
stack[0].dir = 1;
while(top > -1 && !found){
pos = pop();
row = pos.row;
col = pos.col;
dir = pos.dir;
while(dir < 8 && !found){
nextRow = row + move[dir].vert;
nextCol = col + move[dir].horiz;
if(nextRow == exitRow && nextCol == exitCol)
found = TRUE;
else if(!maze[nextRow][nextCol] && !mark[nextRow][nextCol])
{
mark[nextRow][nextCol] = 1;
pos.row = row;
pos.col = col;
pos.dir = ++dir;
push(pos);
row = nextRow;
col = nextCol;
dir = 0;
}
else
++dir;
}
}
if(found) {
printf("the path is:\n");
printf("format:\t(row,col):\n");
for(i = 0; i <= top; i++)
printf("(%d,%d) ", stack[i].row, stack[i].col);
printf("(%d,%d)\n", row, col);
printf("(%d,%d)\n", exitRow, exitCol);
}
else
{
printf("the maze does not have a path\n");
}
}
int main()
{
//
int rows, cols;
printf("******maze question*******\n");
printf("please input maze's size, for example: 3|_|5\n");
scanf("%d %d", &rows, &cols);
makeMaze(rows, cols);
printf("entry: (1,1)\texit:(%d,%d)\n", rows, cols);
for(int i = 0; i < rows+2; i++){
for(int j = 0; j < cols+2; j++)
{
printf("%d ", maze[i][j]);
}
printf("\n");
}
path(rows, cols);
system("pause");
return 0;
}

posted @ 2015-10-25 15:25  hzwackerman  阅读(510)  评论(0编辑  收藏  举报