intisright(int r,int c){ for(int x=0;x<r;x++){//check with previous line if(c==col[x])returnfalse;//if col is not repeated if(abs(col[x]-c)==abs(x-r))returnfalse;//if diagonal is coincided } returntrue; }
1 2 3 4 5 6 7 8 9 10
intdfs(int row){ if(row==n){ans++;print();return0;}//stop circulation for(int i=0;i<n;i++){//try every col if(isright(row,i)){ col[row]=i;//settle dfs(row+1);//recurse col[row]=0;//back } } }
一维数组,下标表示行,值表示列:
1
vector<int>col(8);//val is queen_col,rank is queen_row
int ans,n;//answer,number_row(n*n) vector<int>col(8);//val is queen_col,rank is queen_row
intisright(int r,int c){ for(int x=0;x<r;x++){//check with previous line if(c==col[x])returnfalse;//if col is not repeated if(abs(col[x]-c)==abs(x-r))returnfalse;//if diagonal is coincided } returntrue; }