zoukankan      html  css  js  c++  java
  • [LintCode] N-Queens

    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.

    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.

     
    Example

    There exist two distinct solutions to the 4-queens puzzle:

    [

        [".Q..", // Solution 1

         "...Q",

         "Q...",

         "..Q."],

        ["..Q.", // Solution 2

         "Q...",

         "...Q",

         ".Q.."]

    ]

     1 class Solution {
     2 public:
     3     /**
     4      * Get all distinct N-Queen solutions
     5      * @param n: The number of queens
     6      * @return: All distinct solutions
     7      * For example, A string '...Q' shows a queen on forth position
     8      */
     9     bool isOK(vector<string> &v, int n, int x, int y) {
    10         for (int i = 0; i < x; ++i) 
    11             if (v[i][y] == 'Q') return false;
    12         for (int i = 1; x - i >= 0 && y - i >= 0; ++i) 
    13             if (v[x-i][y-i] == 'Q') return false;
    14         for (int i = 1; x - i >= 0 && y + i < n; ++i)
    15             if (v[x-i][y+i] == 'Q') return false;
    16         return true;
    17     }
    18     void dfs(vector<vector<string>> &res, vector<string> &v, int n, int idx) {
    19         if (idx == n) {
    20             res.push_back(v);
    21             return;
    22         }
    23         for (int i = 0; i < n; ++i) {
    24             v[idx][i] = 'Q';
    25             if (isOK(v, n, idx, i)) dfs(res, v, n, idx + 1);
    26             v[idx][i] = '.';
    27         }
    28     }
    29     vector<vector<string> > solveNQueens(int n) {
    30         // write your code here
    31         vector<vector<string>> res;
    32         string s;
    33         for (int i = 0; i < n; ++i) s.push_back('.');
    34         vector<string> v(n, s);
    35         dfs(res, v, n, 0);
    36         return res;
    37     }
    38 };
  • 相关阅读:
    论程序员的自我修养
    设计模式之:行为型设计模式(11种)
    设计模式之:结构型设计模式(7种)
    @import "../style/lines.scss" 导致background: url()路径无效问题
    node express 设置重定向
    png8和png24的区别
    vue scss 使用 及 踩坑
    js 防抖 节流
    js 次方 开方 对数
    css 修改placeholder样式
  • 原文地址:https://www.cnblogs.com/easonliu/p/4646377.html
Copyright © 2011-2022 走看看