【算法】回溯法-N皇后问题

  • Description

    • 在n×n格的国际象棋盘上摆放n个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问一共有多少种摆法。

  • Input

    • 输入为一个整数,即题面中的n

  • Output

    • 输出为一个整数,即可行的摆法数量

  • Sample Input 1 

1
  • Sample Output 1

1
  • Sample Input 2 

2
  • Sample Output 2

0
  • 代码部分:

#include <stdio.h>

#define MaxNum 500

int diags1[MaxNum];
int diags2[MaxNum]; 
int rows[MaxNum];
int cols[MaxNum];
int state[MaxNum][MaxNum];
int row = 0;
int result = 0;
int n;


void thequeen(){
	if(row == n) {
		result++;
		return;
	}
	for(int col=0; col<n; col++){
		int diag1 = row - col + n - 1;
		int diag2 = row + col;
		if(diags1[diag1] == 0 && diags2[diag2] == 0 && cols[col] ==0){
			state[row][col] = 1;
			cols[col] = diags1[diag1] = diags2[diag2] = 1;
		row++;
		thequeen();	
		state[row][col] = 0;
		cols[col] = diags1[diag1] = diags2[diag2] = 0;
		row--;
		}
	}
}

int main(){
	scanf("%d",&n);
	thequeen();
	printf("%d",result);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值