Solution in C++


  • 0
    P
    class Solution 
    {
    public:
    	vector<vector<string>> solveNQueens(int n) 
    	{
    		int a[30] = {0};
    		vector<vector<string>> rets;
    		for (int i = 0; true;)
    		{
    			int j = a[i];
    			while (j < n) 
    			{
    				if (complict(a, i, j)) ++j;
    				else 
    				{
    					a[i++] = j;
    					break;
    				}
    			}
    			if (i == 0 && a[0] == n) break;
    			if (j == n) 
    			{
    				a[i--] = 0;
    				++a[i];
    			}
    			if (i == n) 
    			{
    				vector<string> ret;
    				for (int i = 0; i < n; ++i)
    				{
    					string temp(n, '.');
    					temp[a[i]] = 'Q';
    					ret.push_back(std::move(temp));
    				}
    				rets.push_back(std::move(ret));
    				--i;
    				++a[i];
    			}
    		}
    
    		return rets;
    	}
    	bool complict(int a[30], int row, int col) 
    	{
    		auto flag = false;
    		for (int i = 0; i < row; ++i)
    		{
    			flag = flag | (col == a[i]) | (row - i == col - a[i]) | (a[i] - col == row - i);
    		}
    		return flag;
    	}
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.