zoukankan      html  css  js  c++  java
  • [leetcode-52-N-Queens II]

    Follow up for N-Queens problem.

    Now, instead outputting board configurations, return the total number of distinct solutions.

    思路:

    典型8皇后,回溯法,验证是否能放皇后位置,判断同一列,左上45°和135°方向。

    bool isValid(vector<string>& nQueens, int row, int col, int &n)
         {
             for (int i = 0; i < row;i++)
             {
                 if (nQueens[i][col] == 'Q')return false;
             }
             for (int i = row - 1, j = col - 1; i >= 0&&j >= 0;i--,j--)
             {
                 if (nQueens[i][j] == 'Q')return false;
             }
             for (int i = row - 1, j = col + 1; i >= 0&&j < n;i--,j++)
             {
                 if (nQueens[i][j] == 'Q')return false;
             }
             return true;
         }
    void totalNQueens(int& n, int row, vector<string>& nQueens, int& total)
         {
             if (row == n)
             {
                 total += 1;
                 return;
             }
             for (int col = 0; col < n;col++)
             {
                 if (isValid(nQueens, row, col, n))
                 {
                     nQueens[row][col] = 'Q';
                     totalNQueens(n, row + 1, nQueens, total);
                     nQueens[row][col] = '.';
                 }
             }
         }
         int totalNQueens(int n)
         {
             vector<string> nQueens(n, string(n, '.'));
             int total = 0;
             totalNQueens(n, 0, nQueens, total);
             return total;
         }
  • 相关阅读:
    新购服务器流程
    nginx代理证书使用方法
    一键部署lnmp脚本
    mysql主从库配置读写分离以及备份
    Linux入门教程(更新完毕)
    Git 工作流程
    Git远程操作
    常用Git命令
    js数组去重
    Sublime Text设置快捷键让html文件在浏览器打开
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6944532.html
Copyright © 2011-2022 走看看