堆栈实现迷宫出路(C语言)

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

#define TRUE 1
#define FALSE 0
#define step 54
#define EXIT_ROW 8
#define EXIT_COL 5
struct element {
	short int row;
	short int col;
	short int dir;
};

typedef struct element element;
element stack[step];
int top;

element push(element item){
	stack[++top] = item;
}

element pop(){
	return stack[top--];
}

struct hehe {
	int vert;
	int horiz;
};
typedef struct hehe hehe;
hehe move[8]={{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};

int mark[9][6]={0};
/*迷宫矩阵,0代表可以走,1代表障碍*/
int maze[9][6]={{0,0,0,0,0,1},{1,1,1,1,1,0},{1,0,0,0,0,1},{0,1,1,1,1,1},{1,0,0,0,0,1},{1,1,1,1,1,0},{1,0,0,0,0,1},{0,1,1,1,1,1},{1,0,0,0,0,0}};
//int maze[1][6]={0};

void path(void)
{ //output a path through the maze if such a path exists
	int i, row, col, nextRow, nextCol, dir, found=FALSE;
	element position;
	//mark[1][1] = 1; 
	top = 0;
	stack[0].row = 0;
	stack[0].col = 0;
	stack[0].dir = 0;
	while (top>-1 && !found) {
		position = pop();
		row = position.row; col = position.col;
		dir = position.dir;
		while (dir<8 && !found) {
			//move in direction dir 
			nextRow = row + move[dir].vert;
			nextCol = col + move[dir].horiz;
			if ((nextRow==EXIT_ROW)&&(nextCol==EXIT_COL))
				found = TRUE;
			else if (!maze[nextRow][nextCol] && !mark[nextRow][nextCol] && nextRow>=0 && nextRow<9 && nextCol>=0 &&nextCol<6) {
				//必须加上边界条件,否则你不知道nextRow或nextCol在数组范围外时会取出什么数字来,有可能就回不到正路上来了
				mark[nextRow][nextCol] = 1;
				position.row = row; position.col = col;
				position.dir = ++dir;
				push(position);
				row = nextRow; col = nextCol;
				dir = 0;
			}
			else ++dir;
		}
	}
	if (found) {
		printf("the path is:\n");
		printf("row  col:\n");
		for (i=0; i<=top; i++)
			printf("%2d%5d\n", stack[i].row, stack[i].col);
		printf("%2d%5d\n", row, col);
		printf("%2d%5d\n", EXIT_ROW, EXIT_COL);
	}
	else printf("The maze does not have a path\n");
}

void main()
{
	int i,j;
	for(i=0;i<9;i++){
		for(j=0;j<6;j++){
			printf("%d  ",maze[i][j]);
		}
		printf("\n");
	}
	path();
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值