首页 > 其他 > 详细

LeetCode N-Queens

时间:2015-03-10 17:14:34      阅读:183      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!