First, n-queensii
1 classSolution {2 Public:3 intTotalnqueens (intN) {4 intTotal =0;5vector<int> V (N,0);6Dfs0, n,total,v);7 returnTotal ;8 }9 Private:Ten BOOLIsvalide (vector<int>& V,intx) { One for(intI=0; i<x;i++){ A if(V[i]==v[x] | | ABS (V[X]-V[I]) ==abs (X-i)) - return false; - } the return true; - } - - voidDfsintCurrintNint& total,vector<int>&v) { + if(Curr = =N) { -total++; + return; A } at - for(intI=0; i<n;i++){ -V[curr] =i; - if(Isvalide (V,curr)) { -DFS (curr+1, n,total,v); - } in } - } to};
Second, N-queens
1 classSolution {2 Public:3vector<vector<string>> Solvenqueens (intN) {4vector<vector<string>>result;5vector<int> V (n,-1);6Dfs0, N,v,result);7 returnresult;8 }9 BOOLIsvalide (vector<int>& V,intCurr) {Ten for(intI=0;i< curr;i++){ One if(V[i] = = V[curr] | | ABS (V[CURR]-V[I]) ==abs (curr-i)) A return false; - } - return true; the } - voidDfsintCurrintn,vector<int>&V, -vector<vector<string>>&result) { - if(Curr = =N) { +vector<string>temp; - for(intI=0; i<n;i++){ + stringS (N,'.'); AS[v[i]] ='Q'; at Temp.push_back (s); - } - Result.push_back (temp); - return; - } - for(intI=0; i<n;i++){ inV[curr] =i; - if(Isvalide (V,curr)) { toDFS (curr+1, N, v,result); + } - } the } *};
Leetcode:n-queens problems