算法学习:回溯解决4皇后问题

回溯解4皇后问题

说实话,到现在对于写代码我还是心里挺害怕的,总觉得自己不行。。。但是我也要坚持下去,没准儿以后就行了呢,哈哈
今天晚上在图书馆复习回溯,老师课件上面第一个就是4皇后问题,我就想着用程序实现一下~~
无从下手,不知道该怎么写,参考了
http://blog.csdn.net/yui/article/details/5946928
写出了自己的代码,写完之后对于回溯有了更加深入的认识,觉得以后写代码之前可以尝试着先写伪代码。
代码来啦~~

#include
using namespace std;

int isconflict(int *x, int k)
{
    for(int i = 1; i < k; i++)
    {
        if(x[i] == x[k] || (x[i] + i) == (x[k] + k) || (x[i] - i) == (x[k] - k))
        {
            return 1;
        }
    }
    return 0;
}

void printresult(int *x, int n)
{
    for(int i = 1; i <= n; i++)
    {
        cout << "第" << i << "行皇后在第" << x[i] << "列" << endl; 

    }
    cout << "*************" << endl;
}

int main()
{
    int n = 4;//皇后数量
    //cout << "请输入皇后数量:";
    //cin >> n;
    int x[n+1];//下标记录皇后所在行,数组中对应的值代表皇后所在的列
    for(int i = 1; i <= n; i++)
    {
        x[i] = 1;
    }
    int k = 1;//从第一个皇后开始搜索
    while(1)
    {
        if(x[k] <= n)
        {
            //如果皇后还在列的可搜索范围内,那么继续判断 
            if(isconflict(x, k))
            {
                x[k]++;
                continue;
            }
            else
            {
                if(k == n)
                {
                    //输出结果
                    printresult(x, n);
                    x[k]++;
                    continue; 
                }
                k++;
                continue; 
            }

        }
        else
        {
            //这一层不行了,得回溯
            if(k > 1)
            {
                x[k] = 1;
                k--;
                x[k]++;
                continue;
            }
            else
            {
                break;
            }
        } 
    } 
    return 0;
}

自己调试程序的能力在提高,觉得Dev-C++的调试不那么智能,过段时间想换一个平台写代码~~

你可能感兴趣的:(算法入门学习)