总排列的数量是 (6! - 2 * 5! + 3!) / 2
重剑无锋,大巧不工
#include <stdio.h> static int path[6]; static int data[6]={1,2,2,3,4,5}; int count; bool IsSafe(int pos,int index) { if( pos == 2 && data[index] == 4) return false; if(pos > 0 && data[path[pos-1]] == 3 && data[index] == 5) return false; if(pos > 0 && data[path[pos-1]] == 5 && data[index] == 3) return false; for( int i = 0; i < pos; i++) if( path[i] == index) return false; if(index == 1) for( int i=0; i < pos; i++) if( path[i] == 2) return false; return true; } void print() { count++; for( int i = 0; i != 6; ++i) printf("%d",data[path[i]]); printf("\t"); } void trial(int pos) { if (pos >= 6) print(); else for(int i=0; i<6;i++) { if(IsSafe(pos,i)) { path[pos]=i; trial(pos+1); } } } int main() { trial(0); printf("\ntotal counts:%d\n",count); return 0; }