八皇后问题,输出各解决方案。
class Solution { public: int count; int <em>x; int *y; int index; bool *rows,</em>cols,<em>ltrb,</em>rtlb; vector<vector<string>> ans; vector<string>item; 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) { x[index] = row; y[index++] = col;<br /> item.clear(); string subitem = ""; for(int j = 0;j < n;j++) { subitem.push_back('.'); } for(int i = 0;i < n;i++) { item.push_back(subitem); } for(int i = 0;i < index;i++) { item[x[i]][y[i]] = 'Q'; } ans.push_back(item); index--; } else { rows[row] = true; cols[col] = true; ltrb[row+col] = true; rtlb[n-1+row-col] = true; x[index] = row; y[index++] = col; Move(row+1,n); index--; rows[row] = false; cols[col] = false; ltrb[row+col] = false; rtlb[n-1+row-col] = false;<br /> } }<br /> } } vector<vector<string> > solveNQueens(int n) {<br /> x = new int[n]; y = new 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); ans.clear(); if(n == 1) { string subitem = "Q"; vector<string>item; item.clear(); item.push_back(subitem); ans.push_back(item); return ans; } int row = 0; index = 0; for(int col = 0;col < n;col++) { rows[row] = true; cols[col] = true; ltrb[row+col] = true; rtlb[n-1+row-col] = true; x[index] = row; y[index++] = col; Move(row+1,n); index--; rows[row] = false; cols[col] = false; ltrb[row+col] = false; rtlb[n-1+row-col] = false; }<br /> return ans; } };