• LeetCode(51) N-Queens


    题目

    The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
    1
    Given an integer n, return all distinct solutions to the n-queens puzzle.

    Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.

    For example,
    There exist two distinct solutions to the 4-queens puzzle:
    2

    分析

    一个经典N皇后问题,这种棋盘类的题目一般是回溯法, 依次放置每行的皇后。要求在放置的时候,要保持当前的状态为合法,即当前放置位置的同一行、同一列、两条对角线上都不存在皇后。

    多种解法请参考

    AC代码

    
    class Solution {
    private:
        vector<vector<string> > ret;
    public:
        vector<vector<string>> solveNQueens(int n) {
            if (n <= 0)
                return vector<vector<string>>();
    
            //二维字符矩阵,存储当前满足N皇后的解
            vector<string> cur(n, string(n, '.'));
    
            //调用主函数
            set_queens(cur, 0);
            return ret; 
        }
    
        void set_queens(vector<string> &cur, int row)
        {
            int size = cur.size();
            if (row == size)
            {
                ret.push_back(cur);
                return;
            }
            else{
                for (int col = 0; col < size; col++)
                {
                    if (isValid(cur, row, col))
                    {
                        cur[row][col] = 'Q';
                        //安置下一个皇后
                        set_queens(cur, row + 1);
                        cur[row][col] = '.';
                    }//for
                }//for
            }
        }
    
        //判断在cur[row][col]位置放一个皇后,是否是合法的状态
        //已经保证了每行一个皇后,只需要判断列是否合法以及对角线是否合法。
        bool isValid(vector<string> &cur, int row, int col)
        {
            //判断是否同列
            for (int i = 0; i < row; i++)
            {
                if (cur[i][col] == 'Q')
                    return false;
            }//for
    
            //判断是否同一左对角线
            for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j)
            {
                if (cur[i][j] == 'Q')
                    return false;
            }
    
            //判断是否同一右对角线
            for (int i = row - 1, j = col + 1; i >= 0 && j <= cur.size(); --i, ++j)
            {
                if (cur[i][j] == 'Q')
                    return false;
            }
    
            return true;
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    webbench 网站压力测试
    php测试工具
    数据库相关文章转载(2) MySQL自带的性能压力测试工具mysqlslap详解
    数据库相关文章转载(1) MySQL性能优化之参数配置
    绿盟RSAS配置小记
    ubuntu14.04 64位安装H3C iNode客户端
    Ubuntu安装iNOde
    CTF中图片隐藏文件分离方法总结
    信息安全铁人三项比赛答案
    360春秋杯CTF比赛WRIteUP
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214829.html
Copyright © 2020-2023  润新知