八皇后问题,输出解法数量即可。
class Solution { public: int count; bool <em>rows,</em>cols,<em>ltrb,</em>rtlb; void SetFalse(bool *arrayin,int n) { for(int i = 0;i < n;i++) arrayin[i] = false; } void Move(int row,int n) { for(int col = 0;col < n;col++) { if( rows[row] != true && cols[col] != true && ltrb[row+col] != true&& rtlb[n-1+row-col] != true) { if(row == n-1)count++; else { rows[row] = true; cols[col] = true; ltrb[row+col] = true; rtlb[n-1+row-col] = true; Move(row+1,n); rows[row] = false; cols[col] = false; ltrb[row+col] = false; rtlb[n-1+row-col] = false;<br /> } }<br /> } } int totalNQueens(int n) { rows = new bool[n];//行 SetFalse(rows,n); cols = new bool[n];//列 SetFalse(cols,n); ltrb = new bool[n+n-1]; SetFalse(ltrb,n+n-1); rtlb = new bool[n+n-1]; SetFalse(rtlb,n+n-1); count = 0; if(n == 1)return 1; int row = 0; for(int col = 0;col < n;col++) { rows[row] = true; cols[col] = true; ltrb[row+col] = true; rtlb[n-1+row-col] = true; Move(row+1,n); rows[row] = false; cols[col] = false; ltrb[row+col] = false; rtlb[n-1+row-col] = false; }<br /> return count; } };