7-22 n queens (10分) 八皇后(n皇后)問題

CCCharon_Ye發表於2020-12-03

7-22 n queens (10分)

there is a chess board with n rows and n columns, you need place n queens in the board,there are no two queens in the same line(include diagonals).

input specification:
input one integer n denotes n queens .

output specification:
place one solution in one line(for example,in the 4 queens,one solution is 2 4 1 3,that means the first row queen will be placed in the 2nd column,the 2nd row queen will be placed in the 4th column,and so on),and output the total solution number in the last line.

input example:

4

output example:

2 4 1 3 
3 1 4 2 
2
#include<bits/stdc++.h>
using namespace std;
int c[20], n, ok, ccount = 0;
void print()
{
	for(int i = 0; i <= n; i++){
		if(i != n) cout << c[i] + 1 << " ";
		else cout << endl;
	}
}
void dfs(int r)
{
	if(r == n){
		print();
		ccount++;
		return ;
	} 
	else{
		for(int i = 0; i < n; i++){
			c[r] = i;
			ok = 1; 
			for(int j = 0; j < r; j++){
				if(c[r] - c[j] == r - j || c[r] - c[j] == j - r || c[r] == c[j]){
					ok = 0;
					break;
				}
			} 
	    	if(ok) dfs(r + 1);
     	}
    }
}
int main()
{
	cin >> n;
	dfs(0);
	cout << ccount; 
	return 0;
}

相關文章