回溯算法经典应用:迷宫求解

 

看这个程序把握两点:

1 栈的作用

2 while+if结构的巧妙应用

 /**//*
    使用回溯法计算迷宫问题
 */
#include <stdio.h>
#include <stdlib.h>
struct pos{
    int row;
    int col;
};
void main(){
    int maze[5][5]={
        0,1,0,1,0,
        0,0,0,1,0,
        0,1,0,1,0,
        0,1,0,0,0,
        0,0,1,1,0
    };                //1表示障碍,0表示可以通过
    int dir=1;        //标记方向:上1左2下3右4
    int i=0;
    int j=0;
    struct pos* stack=(struct pos*)calloc(25,sizeof(struct pos));
    int top=0;
    while(1){
        if(i==4&&j==4){                                //已经找到终点,打印结果
            printf("Finish! The path is: ");
            for(dir=0;dir<top;dir++){
                printf("(");
                printf("%d",stack[dir].row);
                printf(",");
                printf("%d",stack[dir].col);
                printf(") ");
            }
            printf("(4,4)");
            break;
        }
        if(dir==1){
            if( i>0&&*(*(maze+i-1)+j)==0            //下一个位置不越界而且可以通过
                &&!(stack[top-1].row==i-1&&stack[top-1].col==j) ){
                                                    //还需满足:这个将要走的位置不属于刚才走来的路!
                stack[top].row=i;
                stack[top].col=j;
                top++;                                //进栈
                i--;
                dir=1;                                //重置方向标识
            }else{
                dir++;
            }
        }
        else if(dir==2){
            if( j>0&&*(*(maze+i)+j-1)==0
                &&!(stack[top-1].row==i&&stack[top-1].col==j-1) ){
                stack[top].row=i;
                stack[top].col=j;
                top++;
                j--;
                dir=1;
            }else{
                dir++;
            }
        }
        else if(dir==3){
            if( i<4&&*(*(maze+i+1)+j)==0
                &&!(stack[top-1].row==i+1&&stack[top-1].col==j) ){
                stack[top].row=i;
                stack[top].col=j;
                top++;
                i++;
                dir=2;
            }else{
                dir++;
            }
        }
        else{
            if( j<4&&*(*(maze+i)+j+1)==0
                &&!(stack[top-1].row==i&&stack[top-1].col==j+1) ){
                stack[top].row=i;
                stack[top].col=j;
                top++;
                j++;
                dir=1;
            }else{                                        //已经没有别的路了,只有回头
                *(*(maze+i)+j)=1;                        //在回头前标识当前路为不能通过
                i=stack[top-1].row;
                j=stack[top-1].col;
                top--;                                    //出栈
                dir=1;                                    //重置方向标识符
            }
        }
    }
}

你可能感兴趣的:(回溯算法经典应用:迷宫求解)