码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode N-Queens

时间:2015-03-10 17:16:38      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

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.

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

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

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
题意:N皇后问题。

思路:利用回溯做,一行一行的去放,所以我们只要判断列和对角线是否已经存在皇后就行了,当然也可以用标记数组做。

class Solution {
public:

    bool isVaild(vector<string> tmp, int row, int col) {
        for (int i = 0; i < tmp.size(); i++) 
            if (tmp[i][col] == 'Q')
                return false;

        for (int i = row-1, j = col-1; i >= 0 && j >= 0; i--, j--)
            if (tmp[i][j] == 'Q')
                return false;
        for (int i = row-1, j = col+1; i >= 0 && j < tmp.size(); i--, j++)
            if (tmp[i][j] == 'Q')
                return false;
        
        return true;        
    }

    void dfs(vector<vector<string> > &ans, vector<string> &tmp, int cur) {
        if (cur == tmp.size()) {
            ans.push_back(tmp);
            return;
        }

        for (int i = 0; i < tmp.size(); i++) {
            if (isVaild(tmp, cur, i)) {
                tmp[cur][i] = 'Q';
                dfs(ans, tmp, cur+1);
                tmp[cur][i] = '.';
            }
        }
    }

    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > ans;
        vector<string> tmp(n, string(n, '.'));
        dfs(ans, tmp, 0); 
        return ans;
    }
};



LeetCode N-Queens

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/44177413

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!