從新學習c語言 [2]。

原文地址: http://songjinshan.com/akabook/zh/stackqueue.html#stackqueue-dfshtml

#include <stdio.h>

#define MAX_ROW 5
#define MAX_COL 5

struct point{int row, col;} stack[512];
int top = 0;

void push(struct point p){
    stack[top++] = p;
}

struct point pop(void){
    return stack[--top];
}


int is_empty(void){
    return top == 0;
}

int maze[MAX_ROW][MAX_COL] = {
        {0, 1, 0, 0, 0},
        {0, 1, 0, 1, 0},
        {0, 0, 0, 0, 0},
        {0, 1, 1, 1, 0},
        {0, 0, 0, 1, 0}
};

void print_maze(void){
    int i,j;
    for (i = 0; i < MAX_ROW; i++)
    {
        for (j = 0; j < MAX_COL; j++)
        {
            printf("%d ",maze[i][j] );
        }
        putchar('\n');
    }
    printf("***************************\n");
}



struct point predecessor[MAX_ROW][MAX_COL] = {
    {{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1}},
    {{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1}},
    {{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1}},
    {{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1}},
    {{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1}},
};

void print_pre(void){
    int i,j;
    for(i = 0 ; i < MAX_ROW; i++){
        for(j = 0; j < MAX_COL; j++){
            printf("{%d,%d}  ", predecessor[i][j].row,predecessor[i][j].col);
        }
        printf("\n");
    }
}

void visit(int row,int col, struct point pre){
    struct point visit_point = {row,col};
    maze[row][col] = 2;
    predecessor[row][col] = pre;
    printf("visit_point:%d,%d\n",visit_point.row,visit_point.col );
    push(visit_point);
}

int main(void)
{
    struct point p = {0,0};
    maze[p.row][p.col] = 2;
    push(p);
    
    while(!is_empty()){
        p = pop();
        if(p.row == MAX_ROW - 1 && p.col == MAX_COL -1 ) 
                    break;
        if (p.col+1 < MAX_COL && maze[p.row][p.col+1] == 0)
        {
            printf("right\n");
            visit(p.row,p.col+1,p); //右
        }

        if(p.row+1 < MAX_ROW && maze[p.row+1][p.col] == 0){
            printf("down\n");
            visit(p.row+1,p.col,p); //下
        }

        if(p.col-1 >= 0  && maze[p.row][p.col-1] == 0){
            printf("left\n");
            visit(p.col-1,p.row,p); //左
        }

        if(p.row-1 >= 0 && maze[p.row-1][p.col] == 0){
            printf("up\n");
            visit(p.row-1,p.col,p);
        }

        print_maze();
    }

    print_pre();
    if (p.row == MAX_ROW -1 && p.col == MAX_COL -1)
    {
        printf("%d,%d\n", p.row,p.col);
        while(predecessor[p.row][p.col].row != -1){
            p = predecessor[p.row][p.col];
            printf("%d,%d\n", p.row,p.col);
        }
    }else{
        printf("No path\n");
    }
    return 0;
}
相關文章
相關標籤/搜索