/* 题目: N皇后的问题。 */ /* 思路: 全排列。 声明一个具有N个元素的数组curr,每个下标i(0>i>n)代表行,每个curr[i]代表列,所以初始化为curr[i] = i。 此时,各皇后既不在一行也不在一列,只需解决对角线的问题。 当|i-j|==|curr[i]-curr[j]|时,两个皇后处于一个对角线上。 */ #include<iostream> #include<string.h> #include<stdio.h> #include<set> #include<vector> using namespace std; bool isTrue(int* curr,int len){ for(int i = 0; i < len; i++){ for(int j = i+1; j < len; j++){ if(abs(curr[i] - curr[j]) == j - i ){ return false; } } } return true; } void isExist(int* curr,int len,int index,vector<vector<string>> &res){ if(index == len){ if(isTrue(curr,len)){ vector<string> ans; //cout<<"["<<endl; for(int i = 0; i < len; i++){ string row = ""; for(int j = 0; j < len; j++){ row.append("."); } row[curr[i]] = 'Q'; //cout<<row<<","<<endl; ans.push_back(row); } //cout<<"]"<<endl; res.push_back(ans); return; } } for(int i = index; i < len; i++){ int temp = curr[index]; curr[index] = curr[i]; curr[i] = temp; isExist(curr,len,index+1,res); temp = curr[index]; curr[index] = curr[i]; curr[i] = temp; } } vector<vector<string>> solveNQueens(int n) { int curr[n]; vector<vector<string>> res; for(int i = 0; i < n; i++){ curr[i] = i; } isExist(curr,n,0,res); return res; } int main(){ vector<vector<string>> a= solveNQueens(1); for(int i = 0; i < a.size(); i++){ for(int j = 0; j < a[i].size(); j++){ cout<<a[i][j]<<endl; } } }