八皇后问题的两种解法

/******************************************************************************** *FileName: queue.c *Date: 2010/01/15 *Intention: Study various solutions of the Queen problem. *Development Environment: Linux + gcc. *Input: Nums of queen, default to 4. *Output: All solutions. ********************************************************************************/ #include #include #include #include void print_sol(const char arr[], int n) { int i, j; char *map = (char *)malloc(n + 1); assert(NULL != map); memset(map, '-', n); for(i = 0; i < n; i++) { map[arr[i]] = 'x'; printf("%s/n", map); map[arr[i]] = '-'; } free(map); printf("/n"); } char *visit_col = NULL; //n: prevent column conflict. char *visit_main_diagonal = NULL; //2n-1: prevent main diagonal conflict. char *visit_vice_diagonal = NULL; //2n-1: prevent vice diagonal conflict. void queen_sol_one(char sol[], int cur, int num) { int i = 0; if(num == cur) print_sol(sol, num); else for(i = 0; i < num; i++) if(0 == visit_col[i] && 0 == visit_main_diagonal[i-cur + num-1] && 0 == visit_vice_diagonal[i+cur] ) { sol[cur] = i; visit_col[i] = 1; visit_main_diagonal[i-cur + num-1] = 1; visit_vice_diagonal[i+cur] = 1; queen_sol_one(sol, cur+1, num); visit_col[i] = 0; visit_main_diagonal[i-cur + num-1] = 0; visit_vice_diagonal[i+cur] = 0; } } void queen_sol_two(char sol[], int cur, int num) { int i, j; int ok = 0; if(cur == num) print_sol(sol, num); else for(i = 0; i < num; i++) { sol[cur] = i; ok = 1; for(j = 0; j < cur; j++) if(sol[j] == i || sol[cur] - cur == sol[j] - j || sol[cur] + cur == sol[j] + j ) { ok = 0; break; } if(1 == ok) queen_sol_two(sol, cur+1, num); } } int main(int argc, char *argv[]) { int num = 4; char *sol = (char *)malloc(num); assert(sol != NULL); memset(sol, 0, num); visit_col = (char *)malloc(num); assert(NULL != visit_col); memset(visit_col, 0, num); visit_main_diagonal = (char *)malloc(2*num-1); assert(NULL != visit_main_diagonal); memset(visit_main_diagonal, 0, 2*num-1); visit_vice_diagonal = (char *)malloc(2*num-1); assert(NULL != visit_vice_diagonal); memset(visit_vice_diagonal, 0, 2*num-1); if(2 == argc) num = atoi(argv[1]); queen_sol_one(sol, 0, num); queen_sol_two(sol, 0, num); free(sol); free(visit_col); free(visit_main_diagonal); free(visit_vice_diagonal); return 0; } 

 

你可能感兴趣的:(C&C++)