遞歸思想及應用續(二十九)

        今天我們繼續來學習遞歸,下來我們先來回顧下函數的調用過程:在程序運行後有一個特殊的內存區供函數調用使用。那麼這個內存區有什麼用呢?1、用於保存函數中的實參,局部變量,臨時變量等;2、從起始地址開始往一個方向增長(如:高地址 --> 低地址);3、有一個專用“指針”標識當前已使用內存的“頂部”。

        那麼程序中的棧區,就是一段特殊的專用內存區。如下圖所示

圖片.png

        下來我們來看一個示例:逆序打印單鏈表中的偶數結點。如下所示

圖片.png

        下來我們來看看具體源碼是怎麼實現的,如下

#include <iostream>#include <cstring>
#include "DTString.h"
#include "LinkList.h"

using namespace std;
using namespace DTLib;

struct Node
{
    int value;
    Node* next;
};

Node* create_list(int v, int len)
{
    Node* ret = NULL;
    Node* slider = NULL;

    for(int i=0; i<len; i++)
    {
        Node* n = new Node();

        n->value = v++;
        n->next = NULL;

        if( slider == NULL )
        {
            slider = n;
            ret = n;
        }
        else
        {
            slider->next = n;
            slider = n;
        }
    }

    return ret;
}

void destory_list(Node* list)
{
    while( list )
    {
        Node* del = list;

        list = list->next;

        delete del;
    }
}

void print_list(Node* list)
{
    while( list )
    {
        cout << list->value << "->";

        list = list->next;
    }

    cout << "NULL" << endl;
}

void r_print_even(Node* list)
{
    if( list != NULL )
    {
        r_print_even(list->next);

        if( (list->value % 2) == 0)
        {
            cout << list->value << endl;
        }
    }
}

int main()
{
    Node* list = create_list(2, 5);

    print_list(list);

    r_print_even(list);

    return 0;
}

        我們來看看運行結果

圖片.png

        我們看到已經實現了這個功能。

        下來我們來看看著名的“八皇后”問題,那麼什麼是八皇后問題呢?在一個 8×8 的國際棋盤上,有 8 個皇后,每個皇后佔一格;要求皇后間不會出現相互“***”的現象(不能有兩個皇后處於同一行、同一列或同一對角線上)。

圖片.png

        那麼實現的關鍵是什麼呢?我們先來看看關鍵的數據結構定義:

        1、棋盤,它便是用一個二維數組(10*10),0表示位置爲空,1表示皇后,2表示邊界;

        2、位置,struct Pos。

            struct Pos

            {

                int x;

                int y;

            }

        3、方向:

            水平:(-1,0),(1,0)

            垂直:(0,-1),(0,1)

            對角線:(-1,1),(-1,-1),(1,-1),(1,1)

        其中的算法思路:

            1、初始化:j = 1

            2、初始化:i = 1

            3、從第 j 行開始,恢復 i 的有效值(通過函數調用棧進行回溯),判斷第 i 個位置

                a. 位置 i 可放入皇后:標記位置(i,j),j++,轉步驟 2

                b. 位置 i 不可放入皇后:i++,轉步驟 a

                c. 當 i > 8 時,j--,轉步驟 3

            -- 結束:第 8 行有位置可放入皇后。

        下來我們來看看具體的源碼實現,如下

#include <iostream>
#include <cstring>
#include "DTString.h"
#include "LinkList.h"

using namespace std;
using namespace DTLib;

template < int SIZE >
class QueueSolution : public Object
{
protected:
    enum { N = SIZE + 2 };

    struct Pos : public Object
    {
        Pos(int px = 0, int py = 0) : x(px), y(py) { }
        int x;
        int y;
    };

    int m_chessboard[N][N];
    Pos m_direction[3];
    LinkList<Pos> m_solution;
    int m_count;

    void init()
    {
        m_count = 0;

        for(int i=0; i<N; i+=(N-1))
        {
            for(int j=0; j<N; j++)
            {
                m_chessboard[i][j] = 2;
                m_chessboard[j][i] = 2;
            }
        }

        for(int i=1; i<=SIZE; i++)
        {
            for(int j=1; j<=SIZE; j++)
            {
                m_chessboard[i][j] = 0;
            }
        }

        m_direction[0].x = -1;
        m_direction[0].y = -1;
        m_direction[1].x = 0;
        m_direction[1].y = -1;
        m_direction[2].x = 1;
        m_direction[2].y = -1;
    }

    void print()
    {
        for(m_solution.move(0); !m_solution.end(); m_solution.next())
        {
            cout << "(" << m_solution.current().x << ", " << m_solution.current().y << ") ";
        }

        cout << endl;

        for(int i=0; i<N; i++)
        {
            for(int j=0; j<N; j++)
            {
                switch (m_chessboard[i][j])
                {
                    case 0: cout << " "; break;
                    case 1: cout << "#"; break;
                    case 2: cout << "*"; break;
                }
            }

            cout << endl;
        }

        cout << endl;
    }

    bool check(int x, int y, int d)
    {
        bool flag = true;

        do
        {
            x += m_direction[d].x;
            y += m_direction[d].y;
            flag = flag && (m_chessboard[x][y] == 0);
        }
        while( flag );

        return (m_chessboard[x][y] == 2);
    }

    void run(int j)
    {
        if( j <= SIZE )
        {
            for(int i=1; i<=SIZE; i++)
            {
                if( check(i, j, 0) && check(i, j, 1) && check(i, j, 2) )
                {
                    m_chessboard[i][j] = 1;

                    m_solution.insert(Pos(i, j));

                    run(j + 1);

                    m_chessboard[i][j] = 0;

                    m_solution.remove(m_solution.length() - 1);
                }
            }
        }
        else
        {
            m_count++;

            print();
        }
    }

public:
    QueueSolution()
    {
        init();
    }

    void run()
    {
        run(1);

        cout << "Total: " << m_count << endl;
    }
};

int main()
{
    QueueSolution<8> qs;

    qs.run();

    return 0;
}

        我們來看看運行結果

圖片.png

        我們看到總共有 92 種解法。我們來看看四皇后,看看有多少種解法

圖片.png

        我們看到總共有 2 種解法,如上圖所示。通過今天對遞歸的學習,總結如下:1、程序運行後的棧存儲區專供函數調用使用;2、棧存儲區用於保存實參,局部變量,臨時變量等;3、利用棧存儲區能夠方便的實現回溯算法;4、八皇后問題是棧回溯的經典應用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章