走迷宫

来源:互联网 发布:网络充钱的棋牌 编辑:程序博客网 时间:2024/05/01 09:47
/*
     充分了解数据是怎样进栈,怎样出栈,怎样标记以走过的路线,当为零时是可以走的路径
当数据大于零时则表示路径不可走。 

        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");
}
}
原创粉丝点击