请你分别写出对应的伪代码和c语言完整代码
时间: 2024-03-11 13:50:10 浏览: 125
(word完整版)C语言入门必须掌握的75个知识点..doc
伪代码:
```
function solve_n_queens(n):
function is_valid(board, row, col):
for i from 0 to row - 1:
if board[i] == col or abs(board[i] - col) == row - i:
return False
return True
function backtrack(board, row):
if row == n:
result.append(board[:])
else:
for col from 0 to n - 1:
if is_valid(board, row, col):
board[row] = col
backtrack(board, row + 1)
board[row] = -1
result = []
board = [-1] * n
backtrack(board, 0)
return result
```
C语言完整代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool is_valid(int *board, int row, int col, int n) {
for (int i = 0; i < row; i++) {
if (board[i] == col || abs(board[i] - col) == row - i) {
return false;
}
}
return true;
}
void backtrack(int *board, int row, int n, int **result, int *count) {
if (row == n) {
result[*count] = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
result[*count][i] = board[i];
}
(*count)++;
} else {
for (int col = 0; col < n; col++) {
if (is_valid(board, row, col, n)) {
board[row] = col;
backtrack(board, row + 1, n, result, count);
board[row] = -1;
}
}
}
}
int **solve_n_queens(int n, int *returnSize, int **returnColumnSizes) {
int **result = (int **)malloc(100 * sizeof(int *));
int count = 0;
int *board = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
board[i] = -1;
}
backtrack(board, 0, n, result, &count);
*returnSize = count;
*returnColumnSizes = (int *)malloc(count * sizeof(int));
for (int i = 0; i < count; i++) {
(*returnColumnSizes)[i] = n;
}
return result;
}
int main() {
int n = 4;
int returnSize;
int *returnColumnSizes;
int **result = solve_n_queens(n, &returnSize, &returnColumnSizes);
printf("[\n");
for (int i = 0; i < returnSize; i++) {
printf(" [");
for (int j = 0; j < n; j++) {
printf("%d", result[i][j]);
if (j < n - 1) {
printf(", ");
}
}
printf("]");
if (i < returnSize - 1) {
printf(",");
}
printf("\n");
}
printf("]\n");
return 0;
}
```
输出为:
```
[
[1, 3, 0, 2],
[2, 0, 3, 1]
]
```
阅读全文