• 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;
        
    }
  • 相关阅读:
    day04 Java Web 开发入门
    day0203 XML 学习笔记
    canvas 基础
    TreeSet
    IntelliJ IDEA
    elastic-job-lite
    Spring 同一接口注入多个bean实现
    StringRedisTemplate
    小记
    linux 命令
  • 原文地址:https://www.cnblogs.com/Artimis-fightting/p/11264872.html
Copyright © 2020-2023  润新知