走迷宫

/*
     充分了解数据是怎样进栈,怎样出栈,怎样标记以走过的路线,当为零时是可以走的路径
当数据大于零时则表示路径不可走。 

        0 :可走路径

        1:墙壁

        2:走过的路径

       3:回溯路径


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


struct stack_node
{
int x;
int y;

struct stack_node *next;


};
typedef struct stack_node stack_list;
typedef stack_list * link;


link path = NULL;


link push(link stack,int x,int y)//进栈
{
link new_node;

new_node = (link)malloc(sizeof(stack_list));

if(new_node == NULL)
{
printf("failed!\n");
return NULL;
}
new_node->x = x;
new_node->y = y;
new_node->next = stack;
stack = new_node;

return stack;
}


link pop(link stack,int *x,int *y)//出栈
{
link top;

if(stack != NULL)
{
top = stack;
stack = stack->next;
*x = stack->x;
*y = stack->y;

free(top);

return stack;
}
else
{
*x = -1;
}


}
int main(void)
{
int maze[7][10]={1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,1,1,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,0,0,1,1,0,1,0,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1};
int i,j;
int x = 5;
int y = 8;


for(i=0;i<7;i++)
{
for(j=0;j<10;j++)
{
printf("%d ",maze[i][j]);
}
printf("\n");
}


while(x!=1 || y!=1)//是否到达目的地 
{
maze[x][y] = 2;//标记走过的路径 

if(maze[x][y-1] <= 0)//要走的方向(向上走) 
{
y = y-1;
path = push(path,x,y);

}
else if(maze[x+1][y] <= 0)//向右走 
{
x = x+1;
path = push(path,x,y);

}
else if(maze[x-1][y] <= 0)//向左走 
{
x = x-1;
path = push(path,x,y);

}
else if(maze[x][y+1] <= 0)//向下走 
{
y = y+1;
path = push(path,x,y);

}
else
{
maze[x][y] = 3; //回溯路径      
path = pop(path,&x,&y);

}
}
maze[x][y] = 2;

printf("input:\n");//输出迷宫图形 
for(i=1;i<6;i++)
{
for(j=1;j<9;j++)
{
printf("%d ",maze[i][j]);

}
printf("\n");
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值