1.迷宫问题
#include <stdio.h>
#include <stdlib.h>
#define BOUNDARY 8
#define MAX 255
char table[8][8];
int start_x,start_y;
typedef struct Data{
int maze_x;
int maze_y;
}data;
typedef struct Stack{
data* head;
data* tail;
double sum;
}stack;
void init_table()
{
int i,j;
for(i = 0; i < 8; i++)
for(j = 0;j < 8; j++)
table[i][j] = '0';
table[0][0] = '*';
table[7][7] = '*';
table[0][2] = 'x';
table[1][2] = 'x';
table[0][6] = 'x';
table[1][6] = 'x';
table[2][4] = 'x';
table[2][5] = 'x';
table[3][1] = 'x';
table[3][2] = 'x';
table[3][3] = 'x';
table[4][3] = 'x';
table[5][1] = 'x';
table[5][5] = 'x';
table[6][1] = 'x';
table[6][2] = 'x';
table[6][3] = 'x';
table[6][5] = 'x';
table[6][6] = 'x';
table[7][0] = 'x';
}
void show()
{
int i,j;
for(i = 0; i < 8; i++)
{
for(j = 0;j < 8; j++)
printf("%c ",table[i][j]);
printf("\n");
}
}
int is_boundary(int x,int y)//judge whether arrive boundary
{
if((x == BOUNDARY) || (y == BOUNDARY))
return 0;
else
return 1;
}
stack *init_stack()//initialise the stack,the return value is point
{
stack *s = malloc(10*MAX * sizeof(data) + sizeof(double));//derict define stack's member
if(s == NULL)
printf("error!");
// memset(s,0,(MAX * sizeof(data) + sizeof(double)));
s->head = malloc(MAX * sizeof(data));
memset(s->head,0,MAX * sizeof(data));
s->tail = s->head;
s->sum = 0;
return s;
}
void add_stack(stack *s,int x,int y)//add element to stack.
{
s->tail->maze_x = x;
s->tail->maze_y = y;
s->sum ++;
s->tail++;
}
void dele_stack(stack *s)
{
s->tail--;
s->sum--;
}
void start(stack *s,int x,int y)
{
add_stack(s,x,y);
if((table[x][y] == '*') && (start_x != x) && (start_y != y)){
printf("OK!\n");
ok_printf(s);
}
table[x][y] = '1';
if((y>0) && (table[x][y-1] != '1') && (table[x][y-1] != 'x')){
start(s,x,y-1);
}
if((y<7) && (table[x][y+1] != '1') && (table[x][y+1] != 'x')){
start(s,x,y+1);
}
if((x<7) && (table[x+1][y] != '1') && (table[x+1][y] != 'x')){
start(s,x+1,y);
}
if((x>0) && (table[x-1][y] != '1') && (table[x-1][y] != 'x')){
start(s,x-1,y);
}
dele_stack(s);
// return 0;
}
void ok_printf(stack *s)
{
int i;
init_table();
for(i = 0;i < s->sum; i++){
table[s->head->maze_x][s->head->maze_y] = '#';
s->head++;
}
show();
}
int main()
{
init_table();
show();
stack *s = init_stack();
// add_stack(s,0,0);//afferent the origin
start(s,0,0);
free(s);
return 0;
}