Online Judge Solutions

Thursday, November 6, 2014

N-Queens II

Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.


 
class Solution {
public:
    bool canPlace(const vector<int> &placed, int row, int col)
    {
        for (int i = 0; i < row; i++)
        {
            if (placed[i] == col || abs(placed[i]-col) == row-i)
               return false;
        }
        return true;
    }
    
    int totalNQueens(int n) {
        int output = 0;
        vector<int> placed(n, 0);
       
        int row = 0, col = 0;
        while(true) {
            if (col == n) {
                if(row == 0) return output;
                else {
                    row--;
                    col = placed[row]+1;
                    continue;
                }
            }
           
            if (canPlace(placed, row, col)) {
                placed[row] = col;
                if (row == n-1) {
                    output++;
                    col++;
                }
                else {
                    row++;
                    col = 0;
                }
            }
            else
              col++;
        }
    }
}; 

No comments:

Post a Comment