迷宫(多出口)

/*
 * =====================================================================================
 *
 *       Filename:  maze.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2011年12月09日 21时33分32秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *        Company:  
 *
 * =====================================================================================
 */
#include <stdio.h>
#include <stdlib.h>
int b[5][15]= {0};
int cnt_path = 0;
int min = 65535;
/*stack*/
struct stack_node
{
int x;
int y;
struct stack_node *next_ptr;
};


void push(struct stack_node **top_ptr, int x, int y)
{
struct stack_node *new_ptr;
new_ptr = malloc(sizeof(struct stack_node));
if (new_ptr != NULL)
{
new_ptr->x = x;
new_ptr->y = y;
new_ptr->next_ptr = *top_ptr;
*top_ptr = new_ptr;

}
}
void  pop(struct stack_node** top_ptr)
{
struct stack_node* temp_ptr;
temp_ptr = *top_ptr;
*top_ptr = (*top_ptr)->next_ptr;
free(temp_ptr);
}


void print_stack(struct stack_node* current_ptr)
{
if(current_ptr == NULL)
{
printf("the stack is empty.\n");
}
else
{
while(current_ptr != NULL)
{
printf("(%d,%d)\n", current_ptr->x, current_ptr->y);
current_ptr = current_ptr->next_ptr;
}
printf("NULL\n ");
}
}
int is_empty(struct stack_node * top_ptr)
{
return top_ptr == NULL;
}


int find(int a[5][15], int i, int j, int n, int m, struct stack_node *stack_ptr)
{


b[i][j] = 1;
cnt_path++;
push(&stack_ptr, i+1, j+1);


if (a[i][j] == 2)
{
print_stack(stack_ptr);
printf("%d\n", cnt_path);
cnt_path--;
return 0;
}


if (j + 1 < m)//右
{
if (0 != a[i][j+1] && 0 == b[i][j+1] )
{
find(a, i, j+1, n, m,stack_ptr);
}
}


if (i + 1 < n)//下
{
if (0 != a[i+1][j] && 0 == b[i+1][j]) 
{
find(a, i+1, j, n, m,stack_ptr);
}
}


if (j - 1 >= 0 )//左
{
if (0 != a[i][j-1] && 0 == b[i][j-1]) 
{
find(a, i, j-1, n, m,stack_ptr);
}
}


if (i - 1 >= 0)//向上
{
if (0 != a[i-1][j] && 0 == b[i-1][j]) 
{
find(a, i-1, j, n, m,stack_ptr);
}
}

b[i][j] = 0;
cnt_path--;
pop(&stack_ptr);















}


int main()
{
int n,m;
n = 5; 
m = 15; //exit 2 start 3
struct stack_node * stack_ptr = NULL;//在第第一次push的时候NULL会被复制到top_ptr->next_ptr中
int a[5][15] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,1,1,1,1,1,1,1,1,1,1,1,2,0,0,
0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,
0,0,1,0,1,1,1,1,1,1,1,1,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,2,0,0};




find(a, 1, 0, n, m, stack_ptr); //1,0代表出发的坐标,也就是3的坐标




}

你可能感兴趣的:(迷宫(多出口))