关闭

leetcode N-Queens II

888人阅读 评论(0) 收藏 举报
分类:

N-Queens II

 Total Accepted: 1560 Total Submissions: 6035My Submissions

Follow up for N-Queens problem.

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


The code similar to I is TLE

class Solution {
 public:
  bool check(vector<vector<int>>& board, int x, int y) {
    int size = board.size(), xx, yy;
    for (int i = 0; i < x; ++i) 
      if (board[i][y])
        return false;
    for (int i = 0; i < size; ++i) 
      if (board[x][i])
        return false;
    for (xx = --x, yy = --y; xx >= 0 && yy >= 0; --xx, --yy) 
      if (board[xx][yy])
        return false;
    for (xx = --x, yy = ++y; xx >= 0 && yy < size; --xx, ++yy) 
      if (board[xx][yy])
        return false;
    return true;
  }
  void dfs(vector<vector<int>>& board, int& count, int start) {
    int size = board.size();
    if (start == board.size()) {
      ++count;
      return;
    }
    for (int i = 0; i < size; ++i) {
      if (check(board, start, i)) {
        board[start][i] = 1;
        dfs(board, count, start + 1);
        board[start][i] = 0;
      }
    }
  }
  int totalNQueens(int n) {
    if (n == 0)
      return 0;
    int res = 0;
    vector<vector<int>> board(n, vector<int>(n, 0));
    dfs(board, res, 0);
    return res;
  }
};
The main problem is that the check function wastes too much time. 

Two ways to avoid this:

1. Use an array to record the position row[i] , col[i](true, false)

2. BIt manipulation

class Solution {
 public:
  unsigned int upperlimit;
  void dfs(int& count, unsigned int row, unsigned int ld, unsigned int rd) {
    if (row == upperlimit)
      ++count;
    unsigned int pos = (row | ld | rd) & upperlimit; // the bit 1 simplify the position can't place the queue any more
    unsigned int p = (~pos) & upperlimit,digit = 0;
    while (p) {
      digit = p - (p & (p - 1)); // Find the rightest 1
      //digit = p&(~p + 1);
      dfs(count, row + digit, (ld + digit) >> 1, (rd + digit) << 1);
      p -= digit;
    }
  }
  int totalNQueens(int n) {
    upperlimit = 0;
    int count = 0;
    for (int i = 0; i < n; ++i)
      upperlimit |= (1<<i);
    dfs(count, 0, 0, 0);
    return count;
  }
};


This is a WA code, find the problem!!!!!!

class Solution {
 public:
  unsigned int upperlimit;
  int res = 0;
  void dfs(unsigned int row, unsigned int ld, unsigned int rd) {
    if (row == upperlimit)
      ++res;
    unsigned int pos = (row | ld | rd) & upperlimit, p = (~pos) & upperlimit, digit;
    while (p) {
      digit = p - p & (p - 1);
      dfs(row + digit, (ld + digit) << 1, (rd + digit) >> 1);
      p -= digit;
    }
  };
  int totalNQueens(int n) {
    for (int i = 0; i < n; ++i)
      upperlimit |= (1 << i);
    res = 0;
    dfs(0, 0, 0);
    return res;  
  }
};



 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:265546次
    • 积分:4534
    • 等级:
    • 排名:第6492名
    • 原创:152篇
    • 转载:233篇
    • 译文:0篇
    • 评论:6条
    文章分类
    最新评论