C++ clean solution


  • 0
    J
    class Solution {
    public:	
    vector<vector<string> > solveNQueens(int n) {
    	vector<vector<string> > result;
    	vector<int> res(n, -1);
    	solves(result, res, 0);
    	return result;
    }
    void solves(vector<vector<string> >& result, vector<int>& res, int row)
    {
    	for (int i = 0; i < res.size(); i++) {
    		bool isSafe = true;
    		res[row] = i;
    		for (int j = 0; j < row; j++) {
    			if (res[j] == i || abs(i - res[j]) == abs(row - j)) {
    				isSafe = false;
    				break;
    			}
    		}
    
    		if (isSafe && row == res.size() - 1) {
    			string str = "";
    			for (int j = 0; j < res.size(); j++)
    				str += ".";
    
    			vector<string> vStr(res.size(), str);
    			for (int j = 0; j < res.size(); j++)
    				vStr[j][res[j]] = 'Q';
    
    			result.push_back(vStr);
    		}
    		else if (isSafe)
    			solves(result, res, row + 1);
    	}
         }
    };

Log in to reply
 

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