代码:
1 vector<vector<string> > result; 2 void search(int line, int total, vector<string> &v, vector<bool> &col, vector<bool> &left, vector<bool> &right){ 3 if(line == total){ 4 result.push_back(v); 5 return; 6 } 7 int i; 8 for(i = 0; i < total; i++){ 9 if(col[i] && left[line+i] && right[line+total-i-1]){ 10 col[i] = false; 11 left[line+i] = false; 12 right[line+total-i-1] = false; 13 v[line][i] = 'Q'; 14 search(line+1, total, v, col, left, right); 15 v[line][i] = '.'; 16 col[i] = true; 17 left[line+i] = true; 18 right[line+total-i-1] = true; 19 } 20 } 21 } 22 vector<vector<string> > solveNQueens(int n) { 23 // IMPORTANT: Please reset any member data you declared, as 24 // the same Solution instance will be reused for each test case. 25 result.clear(); 26 string s; 27 s.assign(n, '.'); 28 vector<string> v(n, s); 29 vector<bool> col(n, true), left(2*n-1, true), right(2*n-1, true); 30 search(0, n, v, col, left, right); 31 return result; 32 }