比赛描述
检查一个如下的6 x 6的跳棋棋盘,有六个棋子被放置在棋盘上,使得每行、每列最多有一个,每条对角线(包括两条主对角线的所有平行线)上至多有一个棋子。
0 1 2 3 4 5 6 -------------------------1 | | O | | | | | -------------------------2 | | | | O | | | -------------------------3 | | | | | | O | -------------------------4 | O | | | | | | -------------------------5 | | | O | | | | -------------------------6 | | | | | O | | -------------------------
上面的布局可以用序列2 4 6 1 3 5来描述,第i个数字表示在第i行的相应位置有一个棋子,如下:
行号 1 2 3 4 5 6 列号 2 4 6 1 3 5
这只是跳棋放置的一个解。请编一个程序找出所有跳棋放置的解。并把它们以上面的序列方法输出。解按字典顺序排列。请输出前3个解。最后一行是解的总个数。
特别注意: 对于更大的N(棋盘大小N x N)你的程序应当改进得更有效。
输入
多组数据
一个数字N (6 <= N <= 13) 表示棋盘是N x N大小的。
输出
前三行为前三个解,每个解的两个数字之间用一个空格隔开。第四行只有一个数字,表示解的总数。
样例输入
6
样例输出
2 4 6 1 3 5
3 6 2 5 1 4
4 1 5 2 6 3
4
提示
undefined
题目来源
ym
/* Time Limit Exceed at Test 1 #include<iostream> #define MAX_N 14 int num[MAX_N]; bool vst[MAX_N]; int n, count; // 判断在第 pos 行、第 i 列放数字是否合适 bool judge(int pos, int i){ for(int k = 1; k < pos; k++){ if(pos - k == i - num[k] || pos - k == num[k] - i){ return 0; } } return 1; } void dfs(int pos){ if(pos == n){ if(++count <= 3){ printf("%d", num[1]); for(int i = 2; i<= n; ++i){ printf(" %d", num[i]); } printf("\n"); } return; } ++pos; for(int i = 1; i <= n; ++i){ if(!vst[i] && judge(pos, i)){ vst[i] = 1; num[pos] = i; dfs(pos); vst[i] = 0; } } } int main(){ while(scanf("%d", &n) == 1){ count = 0; dfs(0); printf("%d\n", count); } } */ #include<iostream> #define MAX_N 14 int num[MAX_N]; bool vst[MAX_N]; int n, count; // 判断在第 pos 行、第 i 列放数字是否合适 bool judge(int pos, int i){ for(int k = 1; k < pos; k++){ if(pos - k == i - num[k] || pos - k == num[k] - i){ return 0; } } return 1; } void dfs(int pos){ if(count > 3){ return; } if(pos == n){ if(++count <= 3){ printf("%d", num[1]); for(int i = 2; i<= n; ++i){ printf(" %d", num[i]); } printf("\n"); } return; } ++pos; for(int i = 1; i <= n; ++i){ if(!vst[i] && judge(pos, i)){ vst[i] = 1; num[pos] = i; dfs(pos); vst[i] = 0; } } } int main(){ int cou[14]={0,1,0,0,2,10,4,40,92,352,724,2680,14200,73712}; while(scanf("%d", &n) == 1){ count = 0; dfs(0); printf("%d\n", cou[n]); } }