1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class Solution { public: std::vector<std::vector<std::string>> solveNQueens(int n) { std::vector<std::vector<int>> mark; std::vector<std::string> location; std::vector<std::vector<std::string>> result;
for(int i = 0; i < n; i++){ mark.push_back((std::vector<int>() )); for(int j = 0; j < n; j++){
mark[i].push_back(0); } location.push_back(""); location[i].append(n, '.'); }
generate(0, n, mark, location, result);
return result; } private: void put_down_the_queen(int x, int y, std::vector<std::vector<int>> &mark){ static const int dx[] = {-1,1,0,0,-1,-1,1,1}; static const int dy[] = {0,0,-1,1,-1,1,-1,1};
mark[x][y] = 1; for(int i = 0; i < 8 ; i++){ for(int j = 1; j < mark.size() ; j++){ int a = x+j*dx[i]; int b = y+j*dy[i]; if(a < 0 || a >= mark.size() || b < 0 || b > mark.size()){ break; } mark[a][b] = 1; } } }
void generate(int i,int n, std::vector<std::vector<int>> &mark, std::vector<std::string> &location, std::vector<std::vector<std::string>> &result){ if(i == n){ result.push_back(location); return; } for(int j = 0; j < n; j++){ if(mark[i][j]==0){ std::vector<std::vector<int>> temp_mark = mark; put_down_the_queen(i, j, mark); location[i][j] = 'Q'; generate(i+1, n, mark, location,result);
location[i][j] = '.'; mark = temp_mark; }
} }
};
|