codeup eight queens (C ++)

 Title Description

People play chess very clear: the queen can not eat another piece to the number of steps in the horizontal, vertical, diagonal. How eight queens on the chessboard (8 * 8 squares), so that they can not be eaten by anyone! This is the famous eight queens problem. 
8. A method for placement of a queen to meet the requirements of the definition of a corresponding sequence a queen, i.e. a = b1b2 ... b8, where bi is the corresponding number of columns in row i Pendulum Queen located. 8 has been known a total of 92 Queens set of solutions (i.e., 92 different strings Queen).
A given number b, b of the required output strings. String comparison is such that: before Queen Queen disposed string string x y, y if and only if x is smaller than when considered integer.

Entry

Line 1 is the set of n number of test data, followed by n input lines. Each set of test data representing a line, comprising a positive integer b (1 <= b <= 92)

Export

There are n output lines, each output line corresponds to an input. The output should be a positive integer, b is the queen of the corresponding string.

Sample input  Copy

3
6
4
25

Sample output Copy

25713864
17582463
36824175

Problem-solving ideas: the title is actually seeking first eight queens problem b kind of program, the code book can be slightly modified. (His first time to write, do not completely understand the flag [] array of meanings, flag [] array record is the i-th row have no place elements, index of the current record is the first index row), ranks represent possible and the code book different.

#include<bits/stdc++.h>
using namespace std;
int total = 0;
int path[8] = {0};
bool flag[8] = {false};

void quene(int index,int b){   // 依次增加 index 的数值,放置第 index 行的元素 
	if(index == 8){   // 第 8 行(下标为 7)的皇后已经放置好 
		total++;
		if(total == b){   // 当前是所求的第 b 种方案,输出 
			for(int i = 0; i < 8; i++){
				if(i != 7) printf("%d",path[i]+1);
				else printf("%d\n",path[i]+1);
			}
		}
		return;
	}
	for(int i = 0; i < 8; i++){   // 使用回溯法(当该排列中已经出现不合适的组合,则放弃该排列)全排列 b个皇后的位置 
		if(flag[i] == false){    // 第 i 列没有放置皇后
			bool f = true; 		// 假设第 index 行的第 i 列放置皇后 ,当前皇后不与其他各行的皇后冲突  
			for(int j = 0; j < index; j++){   // 遍历之前的皇后,判断不同行不同列的皇后是否在同一对角线上 
				if(abs(j - index) == abs(path[j] - i)){  // 产生冲突 
					f = false;
					break; 
				} 
			}
			if(f){
				path[index] = i;     // 第 index 个皇后,放置在第 index 行第 i 列 
				flag[i] = true;     // 第 i 列放置元素 
				quene(index+1,b);
				flag[i] = false;   // 使用完毕,重置为 false 
			} 
		} 
	}
}
int main(){
	int n;
	scanf("%d",&n);
	while(n--){
		int b;
		scanf("%d",&b);
		path[8] = {0};   // 记录 i 行的皇后放置在 path[i] 列
		flag[8] = {false};  // 记录第 i 列的皇后是否已经放置
		total = 0; 
		quene(0,b);  // 从第 index = 0 行开始求排列方式,求第 b种解决方案 
	}
}

 

Published 32 original articles · won praise 2 · Views 1613

Guess you like

Origin blog.csdn.net/qq_38969094/article/details/104357347