https://leetcode.com/problems/n-queens/
1 classSolution {2 Public:3 voidDFS (vector<vector<string>> &ret, vector<vector<Char>> map,intIintj) {4 if(I==map.size ()-1){5vector<string>ans; ans.clear ();6 for(intKi=0; Ki<map.size (); + +ki) {7 strings="";8 for(intkj=0; kj<map[0].size (); + +kj) {9s+=map[ki][kj];Ten } One Ans.push_back (s); A } - ret.push_back (ans); - return; the } - -vector<vector<Char>>tmp (Map.size ()); - for(intI=0; I<tmp.size (); + +i) tmp.resize (Map.size ()); +TMP =map; - for(intk=0; k<map[0].size (); k++){ + A if(map[i+1][k]=='.')Continue; at - for(intCol=0; col<map[0].size (); + +Col) { - if(map[i+1][col]==' ') map[i+1][col]='.'; - } - for(introw=i+1; Row<map.size (); + +row) { - if(map[row][k]==' ') map[row][k]='.'; in } - for(introw=i+2, col=k+1; Row<map.size () && col<map[0].size (); ++row,++Col) { to if(map[row][col]==' ') map[row][col]='.'; + } - for(introw=i+2, col=k-1; Row<map.size () && col>=0; ++row,--Col) { the if(map[row][col]==' ') map[row][col]='.'; * } $map[i+1][k]='Q';Panax Notoginseng -DFS (ret,map,i+1, k); the +map=tmp; A } the + } -vector<vector<string>> Solvenqueens (intN) { $vector<vector<string>>ret; $ if(n==0)returnret; - -vector<vector<Char>>map (n); the for(intI=0; I<map.size (); + +i) map[i].resize (n); - for(intI=0; I<map.size (); + +i) {Wuyi for(intj=0; J<map[i].size (); ++j) map[i][j]=' '; the } - Wuvector<vector<Char>>tmp (Map.size ()); - for(intI=0; I<tmp.size (); + +i) tmp.resize (Map.size ()); AboutTMP =map; $ for(intk=0; k<map[0].size (); k++){ - for(intCol=0; col<map[0].size (); ++col) map[0][col]='.'; - for(introw=0; Row<map.size (); ++row) map[row][k]='.'; - for(introw=1, col=k+1; Row<map.size () && col<map[0].size (); ++row,++col) map[row][col]='.'; A for(introw=1, col=k-1; Row<map.size () && col>=0; ++row,--Col) map[row][col]='.'; +map[0][k]='Q'; the -DFS (Ret,map,0, k); $ themap=tmp; the } the the returnret; - } in};
[email protected] [51/52] N-queens