• 当前位置:首页>>C语言>>C语言编程实例>>用递归法解决商人渡河问题
  • 用递归法解决商人渡河问题
  •                                            作者:曹开锐

            递归确实是一种很了不起的方法,但是我感觉实在是太难掌握了,递归法可以用栈转换成为非递归法,但是递归法可以使程序简单,用递归法解决的n皇后问题,还有汉诺塔问题,迷宫问题。。。。。。

            商人渡河问题是这样的:有三个商人,三个强盗,和一条船(船每次只可以载小于等于两个人)他们同在河的一边,想渡过河去,但是必须保证在河的任何一边必须保证商人的数目大于等于强盗的数目,应该怎么过这条河呢?

    用递归的源程序如下:

    开始时商人,强盗所在的河的这边设为0状态,另一边设为1状态(也就是船开始时的一边设为0,当船驶到对岸是设为1状态,在这两个状态时,都必须符合条件)

    #include<stdlib.h>

    struct node                        /*建立一个类似栈的数据结构并且可以浏览每一个数据点*/
    {
        int x;
        int y;
        int state;
        struct node *next;
    };

    typedef struct node state;
    typedef state *link;
    link PPointer1=NULL;
    link PPointer2=NULL;
    int a1,b1;
    int a2,b2;
                                                   /*栈中每个数据都分为0,1状态*/
    void Push(int a,int b,int n)                  
    {
        link newnode;
        newnode=(link)malloc(sizeof(state));
        newnode->x=a;
        newnode->y=b;
        newnode->state=n;
        newnode->next=NULL;
        if(PPointer1==NULL)
            {
                PPointer1=newnode;
                PPointer2=newnode;
            }
            else
            {
                PPointer2->next=newnode;
                PPointer2=newnode;
            }
    }

    void Pop()                            /*弹栈*/
    {
        link pointer;
        if(PPointer1==PPointer2)
        {
            free(PPointer1);
            PPointer1=NULL;
            PPointer2=NULL;
        }
        pointer=PPointer1;
        while(pointer->next!=PPointer2)
            pointer=pointer->next;
        free(PPointer2);
        PPointer2=pointer;
        PPointer2->next=NULL;
    }


    int history(int a,int b,int n)              /*比较输入的数据和栈中是否有重复的*/
    {
        link pointer;
        if(PPointer1==NULL)
                return 1;
        else
        {
            pointer=PPointer1;
            while(pointer!=NULL)
            {
                if(pointer->x==a&&pointer->y==b&&pointer->state==n)
                    return 0;
                pointer=pointer->next;
            }
            return 1;
        }
    }

    [1] [2] [3] [4] 下一页