1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include <stdio.h> #include <stdbool.h> #include <stdlib.h>
bool is_safe(int board[], int row, int col, int n) { for (int i = 0; i < row; i++) { if (board[i] == col || board[i] - i == col - row || board[i] + i == col + row) { return false; } } return true; }
bool solve_n_queens(int board[], int row, int n) { if (row == n) { return true; } for (int col = 0; col < n; col++) { if (is_safe(board, row, col, n)) { board[row] = col; if (solve_n_queens(board, row + 1, n)) { return true; } } } return false; }
bool is_valid_sudoku(int board[9][9], int row, int col, int num) { for (int x = 0; x < 9; x++) { if (board[row][x] == num) { return false; } } for (int x = 0; x < 9; x++) { if (board[x][col] == num) { return false; } } int start_row = row - row % 3; int start_col = col - col % 3; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i + start_row][j + start_col] == num) { return false; } } } return true; }
bool solve_sudoku(int board[9][9]) { for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (board[row][col] == 0) { for (int num = 1; num <= 9; num++) { if (is_valid_sudoku(board, row, col, num)) { board[row][col] = num; if (solve_sudoku(board)) { return true; } board[row][col] = 0; } } return false; } } } return true; }
int main() { int n = 8; int* board = (int*)malloc(n * sizeof(int)); if (solve_n_queens(board, 0, n)) { printf("8皇后解: "); for (int i = 0; i < n; i++) { printf("(%d,%d) ", i, board[i]); } printf("\n"); } free(board); return 0; }
|