zoukankan      html  css  js  c++  java
  • DFS解决八皇后问题

    2019-07-29

    16:49:15

    #include <bits/stdc++.h>
    using namespace std;
    int mat[100][100];
    int tot;
    
    int check(int row, int col)
    {
        for(int i = 1; i <= row; i++)
        {
            if(mat[i][col] == 1) //只需要判断在这一列是否已经方了 
            {
                return 0;
            }
            //判断主副对角线 
            for(int j = 1; j < 9; j++)
            {
                if(mat[i][j] == 1)
                {
    //                if (i + j == row + col )
    //                {
    //                    return 0;
    //                }
    //                else if(fabs(i - j) == fabs(row - col))
    //                {
    //                    return 0;
    //                }
                    if(fabs(i - row) - fabs(j - col) == 0) //等腰梯形 
                    {
                        return 0;
                    }
                    else
                    {
    //                    continue;
                        break;
                    }
                    
                }
            }
            
        }
        return 1;
    }
    
    void dfs(int row)
    {
        if(row == 9)
        {
            tot++;
            for(int i = 1; i < 9; i++)
            {
                for(int j = 1; j < 9; j++)
                {
                    cout << mat[i][j] << " ";
                }
                cout << endl;
            }
            cout << endl;
        }
        else
        {
            for(int col = 1; col < 9; col++)
            {
                if(check(row, col) == 1)
                {
                    mat[row][col] = 1;
                    dfs(row + 1);
                    mat[row][col] = 0;
                }
            }
        }
    }
    int main()
    {
        dfs(1);
        cout << "tot = " << tot << endl;
        return 0;
        
    }
  • 相关阅读:
    css 图片的无缝滚动
    有时间研究下这个
    js的类数组对象
    js的this什么时候会出现报错
    js前端分页
    js队列
    js前端处理url中的参数为对象
    随机看的一点代码
    js的callee和caller方法
    js的Object和Function
  • 原文地址:https://www.cnblogs.com/Artimis-fightting/p/11264872.html
Copyright © 2011-2022 走看看