迷宫问题

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

#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;
}

转载于:https://www.cnblogs.com/hzwackerman/p/4908820.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值