c语言实现迷宫问题(栈)

#include"\header1.h"
#define N 5

void makeprint(int map[][N],pos p) {
map[p.x][p.y] = 3;//不能走/死胡同标记为3
}

pos nexpos(pos curpos, int i) {//走的顺序:顺时针
switch (i) {
{
case 1:curpos.y++;
break;
case 2:curpos.x++;
break;
case 3:curpos.y–;
break;
case 4:curpos.x–;
break;
default:
break;
}
}
return curpos;
}

//足迹
void foot(int map[][N],pos curpos) {
map[curpos.x][curpos.y] = -1;//足迹,走过-1表示
}

//当前点是不是可以走
bool pass(int map[][N],pos curpos) {
if (map[curpos.x][curpos.y] == 0) {//为0表示可以走
return true;
}
else {
return false;
}
}

创建迷宫
void creat(int map[][N], int i, int j) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
map[i][j] = 0;
}
}
for (int m = 0; m < j; m++) {
map[0][m] = 1;
map[N - 1][m] = 1;
map[m][0] = 1;
map[m][N - 1] = 1;
}
map[1][3] = 1;
map[2][2] = 1;
}

//输出迷宫
void showmaze(int map[][N], int i, int j) {
for (int m = 0; m < N; m++) {
for (int n = 0; n < N; n++) {
printf("%d\t", map[m][n]);
}
printf("\n\n");
}
}

//迷宫路径走法
void maze(int map[][N], pos start, pos end) {
Stack L;
InitStack(L);
pos curpos = start;
do
{
//当前位置可以通行
if (pass(map, curpos)) {
Elemtype p;
foot(map,curpos);
p.dir = 1;
p.e = curpos;
push(L, p);//可以走就入栈
curpos = nexpos(curpos, 1);
if (curpos.x == end.x && curpos.y == end.y) {//栈中存放的就是路径点
Elemtype e;
while (!empty(L)) {//从栈里面弹出来就是路径
pop(L, e);
map[e.e.x][e.e.y] = 2;
}
for (int a = 0; a < N; a++){//优化掉不能走的地方
for (int n = 0; n < N; n++) {
if (map[a][n] == 3) {
map[a][n] = 0;
}
}
}
map[end.x][end.y] = 2;
return;
}
}
else {//当前位置不能通过
if (!empty(L)) {
Elemtype p;
pop(L, p);
while (p.dir == 4 && !empty(L)) {//四周都走过了
makeprint(map,p.e);
pop(L, p);
}
if (p.dir < 4) {//找四周可以通过的地方
p.dir++;
curpos = p.e;
curpos = nexpos(curpos, p.dir);//下一步
push(L, p);//把当前压入栈中
}
}
}
} while (!empty(L));

}
int main(){
int map[N][N];
pos start, end;
creat(map, N, N);
showmaze(map, N, N);
printf(“input the start and end postion:”);
scanf_s("(%d,%d)(%d,%d)",&start.x, &start.y, &end.x, &end.y);
maze(map,start,end);
showmaze(map, N, N);
return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值