leetcode系列(60)N-Queens, N-Queens II

来源:互联网 发布:东盟共同体 知乎 编辑:程序博客网 时间:2024/05/17 01:35

N-Queues

The n-queens puzzle is the problem of placing n queenson an n×n chessboard such that no two queens attackeach other.


Given an integer n, return all distinct solutions to the n-queenspuzzle.

Each solution contains a distinct board configuration of the n-queens'placement, where 'Q' and '.' both indicate a queen and anempty 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-Queues II

Follow up for N-Queens problem.

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

解答这个题目版本II的难度居然比版本I低,I是需要给出所有解,II只需要给出解的个数即可。这个题目和Sudoku Solver问题类似,用backtracking去暴力试。首先明确一下国际象棋皇后的规则,皇后和中国象棋里面的车很像(所在行与列都是攻击范围)而且还多了一个feature就是所在斜线也是工具范围(当然这些斜线都是45',135')。那么如何标记已经放置的皇后呢?用一个一维数组就很方便表示了(因为一行只能有一个皇后,而且我们是一行一行的放置皇后,这样只需要判断所在列和斜线是否有皇后),设cols[N]为该数组,i表示[0,N)行, <i, cols[i]>表示一个皇后的位置;这样对于一个坐标<row, col>,只需要遍历cols:

  1.   cols[i] == col 判断<row, col>所在列是否已经有皇后
  2.   abs(row - i) == abs(col -cols[i])判断<row, col>判断所在斜线是否已经有皇后

代码如下:

N-Queue

class Solution {public:    vector<vector<string>> solveNQueens(int n) {        vector<int> cols(n, -1);        vector<vector<string>> ret;        _solveNQ(ret, cols, 0, n);        return ret;    }private:    void _solveNQ(vector<vector<string>>& ret, vector<int>& cols, int row, int size) {        if (row == size) {            vector<string> cur_solution;            for (int i = 0; i < size; ++i) {                string cur_row(size, '.');                for (int j = 0; j < size; ++j) {                    if (j == cols[i]) {                        cur_row[j] = 'Q';                    }                       }                cur_solution.push_back(cur_row);            }            ret.push_back(cur_solution);        } else {            for (int c = 0; c < size; ++c) {                if (!_isValid(cols, row, c)) {                    continue;                }                cols[row] = c;                _solveNQ(ret, cols, row + 1, size);                cols[row] = -1;            }        }    }        bool _isValid(const vector<int>& cols, int row, int col) {        for (size_t i = 0; i < cols.size(); ++i) {            if (col == cols[i] || std::abs(row - i) == std::abs(col - cols[i])) {                return false;            }        }        return true;    }};

N-Queue II

class Solution {public:    int totalNQueens(int n) {        vector<int> cols(n, -1);        int ret = 0;        _solveNQ(ret, cols, 0, n);        return ret;    }private:    void _solveNQ(int& ret, vector<int>& cols, int row, int size) {        if (row == size) {            ++ret;        } else {            for (int c = 0; c < size; ++c) {                if (!_isValid(cols, row, c)) {                    continue;                }                cols[row] = c;                _solveNQ(ret, cols, row + 1, size);                cols[row] = -1;            }        }    }        bool _isValid(const vector<int>& cols, int row, int col) {        for (size_t i = 0; i < cols.size(); ++i) {            if (col == cols[i] || std::abs(row - i) == std::abs(col - cols[i])) {                return false;            }        }        return true;    }};



0 0
原创粉丝点击