测试大模型八皇后求解,模型是DeepSeek-R1-0528和Kimi-k2-0711-preview
文章摘要: 本文对比了DeepSeek-R1-0528和Kimi-k2-0711-preview两个大模型在解决八皇后问题上的表现。测试包含Python、Mojo和C语言三种实现方式。结果显示:1)在Python实现中,两者均能正确解决问题,但Kimi的交互性更优;2)对新兴语言Mojo,两者均未能成功运行;3)在C语言实现中,两者代码均能一次通过,Kimi提供了更丰富的功能(如位运算优化和交互式
2024年发过一篇对比大模型的文章:https://skywalk.blog.csdn.net/article/details/139049626
经过一年多的发展,现在大模型写程序都已经比以前有了天翻地覆的进步!
咱们先来个匿名比较,最后会揭晓谜底!
求解prompt:请用python语言写八皇后放置到一张棋盘的问题解决代码
模型1
def solve_n_queens(n=8):
def is_safe(row, col):
# 检查同一列是否有皇后
for prev_row in range(row):
if board[prev_row] == col or \
board[prev_row] - prev_row == col - row or \
board[prev_row] + prev_row == col + row:
return False
return True
def place_queen(row):
# 所有行都放置完毕,找到一组解
if row == n:
solutions.append(board[:])
return
# 尝试在当前行的每一列放置皇后
for col in range(n):
if is_safe(row, col):
board[row] = col # 放置皇后
place_queen(row + 1) # 递归放置下一行
# 初始化棋盘:board[i] = j 表示第i行皇后放在第j列
board = [-1] * n
solutions = []
place_queen(0) # 从第0行开始放置
return solutions
def print_board(solution):
n = len(solution)
for row in range(n):
line = ""
for col in range(n):
line += "Q " if solution[row] == col else ". "
print(line)
print()
# 解决八皇后问题
solutions = solve_n_queens()
# 输出结果
print(f"总共有 {len(solutions)} 种解法")
if solutions:
print("\n其中一种解法:")
print_board(solutions[0])
输出结果
总共有 92 种解法
其中一种解法:
Q . . . . . . .
. . . . Q . . .
. . . . . . . Q
. . . . . Q . .
. . Q . . . . .
. . . . . . Q .
. Q . . . . . .
. . . Q . . . .
模型2
代码
class EightQueens:
def __init__(self, n=8):
self.n = n
self.solutions = [] # 存储所有解
self.count = 0 # 解的计数
def solve(self):
"""求解八皇后问题"""
# 用一维数组表示:board[i] = j 表示第i行第j列有皇后
board = [-1] * self.n
self._backtrack(board, 0)
return self.solutions
def _backtrack(self, board, row):
"""回溯搜索"""
if row == self.n:
# 找到一个完整解
self.solutions.append(board.copy())
self.count += 1
return
for col in range(self.n):
if self._is_valid(board, row, col):
board[row] = col
self._backtrack(board, row + 1)
# 回溯:不需要显式重置,因为会被覆盖
def _is_valid(self, board, row, col):
"""检查在(row, col)放置皇后是否合法"""
for i in range(row):
# 检查同列
if board[i] == col:
return False
# 检查对角线(行差 == 列差)
if abs(board[i] - col) == abs(i - row):
return False
return True
def print_solution(self, solution_index=0):
"""打印指定解的棋盘"""
if not self.solutions:
print("请先调用solve()求解")
return
if solution_index >= len(self.solutions):
print(f"只有{len(self.solutions)}个解,索引{solution_index}超出范围")
return
board = self.solutions[solution_index]
print(f"\n{'='*25} 第 {solution_index + 1} 个解 {'='*25}")
# 打印列号
print(" ", end="")
for i in range(self.n):
print(f" {i} ", end="")
print()
print(" +" + "---" * self.n + "+")
# 打印棋盘
for row in range(self.n):
print(f"{row} |", end="")
for col in range(self.n):
if board[row] == col:
print(" Q ", end="") # 皇后
else:
print(" . ", end="") # 空位
print("|")
print(" +" + "---" * self.n + "+")
print(f"皇后位置: {board}")
def print_all_solutions(self, max_display=5):
"""打印多个解"""
print(f"\n{'='*50}")
print(f"八皇后问题共有 {self.count} 个解")
print(f"{'='*50}")
display_count = min(max_display, self.count)
for i in range(display_count):
self.print_solution(i)
if self.count > max_display:
print(f"\n... 还有 {self.count - max_display} 个解未显示")
# ============ 使用示例 ============
def main():
# 创建求解器
solver = EightQueens(n=8)
# 求解
print("正在求解八皇后问题...")
solver.solve()
# 打印结果
solver.print_all_solutions(max_display=3)
# 交互式查看特定解
while True:
try:
choice = input("\n输入解的编号查看(1-{},0退出): ".format(solver.count))
idx = int(choice) - 1
if idx == -1:
break
if 0 <= idx < solver.count:
solver.print_solution(idx)
else:
print("编号超出范围")
except ValueError:
print("请输入有效数字")
# 运行
if __name__ == "__main__":
main()
输出
正在求解八皇后问题...
==================================================
八皇后问题共有 92 个解
==================================================
========================= 第 1 个解 =========================
0 1 2 3 4 5 6 7
+------------------------+
0 | Q . . . . . . . |
1 | . . . . Q . . . |
2 | . . . . . . . Q |
3 | . . . . . Q . . |
4 | . . Q . . . . . |
5 | . . . . . . Q . |
6 | . Q . . . . . . |
7 | . . . Q . . . . |
+------------------------+
皇后位置: [0, 4, 7, 5, 2, 6, 1, 3]
========================= 第 2 个解 =========================
0 1 2 3 4 5 6 7
+------------------------+
0 | Q . . . . . . . |
1 | . . . . . Q . . |
2 | . . . . . . . Q |
3 | . . Q . . . . . |
4 | . . . . . . Q . |
5 | . . . Q . . . . |
6 | . Q . . . . . . |
7 | . . . . Q . . . |
+------------------------+
皇后位置: [0, 5, 7, 2, 6, 3, 1, 4]
========================= 第 3 个解 =========================
0 1 2 3 4 5 6 7
+------------------------+
0 | Q . . . . . . . |
1 | . . . . . . Q . |
2 | . . . Q . . . . |
3 | . . . . . Q . . |
4 | . . . . . . . Q |
5 | . Q . . . . . . |
6 | . . . . Q . . . |
7 | . . Q . . . . . |
+------------------------+
皇后位置: [0, 6, 3, 5, 7, 1, 4, 2]
... 还有 89 个解未显示
输入解的编号查看(1-92,0退出):
总结
都完成的挺好
求解prompt:使用mojo语言,写8皇后放置解决方法程序
模型1报错
ojo queens.mojo
/home/skywalk/mojowork/queens.mojo:1:6: error: unable to locate module 'tensor'
from tensor import Tensor
^
/home/skywalk/mojowork/queens.mojo:2:12: error: unable to locate module 'list'
from utils.list import List
^
/home/skywalk/mojowork/queens.mojo:4:18: error: package 'time' does not contain 'now'
from time import now
^
/home/skywalk/mojowork/queens.mojo:114:5: error: use of unknown declaration 'let'
let size_input = input()
^~~
/home/skywalk/mojowork/queens.mojo:114:9: error: statements must start at the beginning of a line
let size_input = input()
^
/home/skywalk/mojowork/queens.mojo:108:8: warning: doc string summary should end with a period '.', but this ends with ''
"""主函数"""
/home/skywalk/.local/bin/mojo: error: failed to parse the provided Mojo source module
模型2报错
mojo eight_queen.mojo
/home/skywalk/mojowork/eight_queen.mojo:95:8: warning: doc string summary should end with a period '.', but this ends with ''
"""使用位运算优化的八皇后求解器"""
/home/skywalk/mojowork/eight_queen.mojo:11:23: error: expected ')' in argument list
fn __init__(inout self, n: Int = 8):
^
/home/skywalk/mojowork/eight_queen.mojo:214:26: error: use of unknown declaration 'now'
var start_time = now() # 需要导入时间模块
/home/skywalk/mojowork/eight_queen.mojo:101:23: error: expected ')' in argument list
fn __init__(inout self, n: Int = 8):
^
/home/skywalk/mojowork/eight_queen.mojo:208:8: warning: doc string summary should end with a period '.', but this ends with ''
"""测试不同规模的N皇后问题"""
/home/skywalk/mojowork/eight_queen.mojo:31:31: error: expected ')' in argument list
fn _solve_recursive(inout self, inout board: List[Int], row: Int):
^
/home/skywalk/mojowork/eight_queen.mojo:48:20: error: expected ')' in argument list
fn solve(inout self):
^
/home/skywalk/mojowork/eight_queen.mojo:61:9: error: use of unknown declaration 'let'
let solution = self.solutions[index]
^~~
/home/skywalk/mojowork/eight_queen.mojo:61:13: error: statements must start at the beginning of a line
let solution = self.solutions[index]
^
/home/skywalk/mojowork/eight_queen.mojo:109:29: error: expected ')' in argument list
fn _solve_bitwise(inout self, row: Int, cols: Int, diags1: Int, diags2: Int):
^
/home/skywalk/mojowork/eight_queen.mojo:146:20: error: expected ')' in argument list
fn solve(inout self):
^
/home/skywalk/.local/bin/mojo: error: failed to parse the provided Mojo source module
总结
对新编程语言mojo,支持的还是不行,无法一次性成功。改了一次代码后,也没有成功!
求解prompt:使用c语言,写8皇后放置解决方法程序
模型1
代码
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#define N 8 // 棋盘大小(8x8)
// 全局计数器
int solution_count = 0;
// 打印棋盘
void print_board(int board[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j])
printf("Q ");
else
printf(". ");
}
printf("\n");
}
printf("\n");
}
// 检查在给定位置放置皇后是否安全
bool is_safe(int board[N][N], int row, int col) {
int i, j;
// 检查该列是否有皇后
for (i = 0; i < row; i++) {
if (board[i][col])
return false;
}
// 检查左上对角线
for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j])
return false;
}
// 检查右上对角线
for (i = row, j = col; i >= 0 && j < N; i--, j++) {
if (board[i][j])
return false;
}
return true;
}
// 递归放置皇后函数
bool solve_n_queens(int board[N][N], int row) {
// 所有皇后都已放置,打印解决方案
if (row == N) {
solution_count++;
printf("解法 #%d:\n", solution_count);
print_board(board);
return true; // 返回true继续查找所有解
}
bool res = false;
for (int col = 0; col < N; col++) {
if (is_safe(board, row, col)) {
// 放置皇后
board[row][col] = 1;
// 递归放置下一行的皇后
res = solve_n_queens(board, row + 1) || res;
// 回溯:移除皇后
board[row][col] = 0;
}
}
return res; // 返回是否找到解决方案
}
// 主函数
int main() {
int board[N][N] = {0}; // 初始化棋盘全为0
printf("八皇后问题求解器\n");
printf("----------------\n");
clock_t start = clock();
// 开始放置皇后
if (!solve_n_queens(board, 0)) {
printf("未找到解决方案!\n");
}
clock_t end = clock();
double time_taken = (double)(end - start) / CLOCKS_PER_SEC;
printf("总共找到 %d 种解法\n", solution_count);
printf("求解耗时: %.6f 秒\n", time_taken);
return 0;
}
输出:
./queen2.out
八皇后问题求解器
----------------
解法 #1:
Q . . . . . . .
. . . . Q . . .
. . . . . . . Q
. . . . . Q . .
. . Q . . . . .
. . . . . . Q .
. Q . . . . . .
. . . Q . . . .
解法 #2:
Q . . . . . . .
. . . . . Q . .
. . . . . . . Q
. . Q . . . . .
. . . . . . Q .
. . . Q . . . .
. Q . . . . . .
. . . . Q . . .
模型2
// eight_queens.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 8
#define MAX_SOLUTIONS 100
// ============ 全局变量 ============
int solutions[MAX_SOLUTIONS][N]; // 存储所有解
int solution_count = 0; // 解的计数
// ============ 基础回溯版本 ============
// 检查在 (row, col) 放置皇后是否安全
int is_safe(int board[N], int row, int col) {
for (int i = 0; i < row; i++) {
// 检查同列
if (board[i] == col) {
return 0;
}
// 检查对角线
if (abs(board[i] - col) == abs(i - row)) {
return 0;
}
}
return 1;
}
// 递归回溯求解
void solve_n_queens(int board[N], int row) {
if (row == N) {
// 找到一个解,保存
for (int i = 0; i < N; i++) {
solutions[solution_count][i] = board[i];
}
solution_count++;
return;
}
for (int col = 0; col < N; col++) {
if (is_safe(board, row, col)) {
board[row] = col;
solve_n_queens(board, row + 1);
// 回溯:无需显式恢复,会被覆盖
}
}
}
// ============ 位运算优化版本 ============
// 使用位运算的快速求解(只计数,不存储)
void solve_n_queens_fast(int row, int cols, int diags1, int diags2, int *count) {
if (row == N) {
(*count)++;
return;
}
// 计算可用位置:~ (cols | diags1 | diags2) 取低N位
int available = ~(cols | diags1 | diags2) & ((1 << N) - 1);
while (available) {
// 取最低位的1
int pos = available & -available;
available -= pos;
int col = __builtin_ctz(pos); // 计算pos中1的位置(GCC内置函数)
solve_n_queens_fast(
row + 1,
cols | pos,
(diags1 | pos) << 1,
(diags2 | pos) >> 1,
count
);
}
}
// 兼容版本(不使用GCC内置函数)
void solve_n_queens_fast_compat(int row, int cols, int diags1, int diags2, int *count) {
if (row == N) {
(*count)++;
return;
}
int available = ~(cols | diags1 | diags2) & ((1 << N) - 1);
while (available) {
int pos = available & -available;
available -= pos;
// 手动计算位数
int col = 0;
int p = pos;
while (p >>= 1) col++;
solve_n_queens_fast_compat(
row + 1,
cols | pos,
(diags1 | pos) << 1,
(diags2 | pos) >> 1,
count
);
}
}
// ============ 打印功能 ============
// 打印单个解的棋盘
void print_board(int solution[N]) {
printf("\n ");
for (int i = 0; i < N; i++) {
printf("%d ", i);
}
printf("\n +");
for (int i = 0; i < 2 * N + 1; i++) printf("-");
printf("+\n");
for (int row = 0; row < N; row++) {
printf("%d |", row);
for (int col = 0; col < N; col++) {
if (solution[row] == col) {
printf("Q ");
} else {
printf(". ");
}
}
printf("|\n");
}
printf(" +");
for (int i = 0; i < 2 * N + 1; i++) printf("-");
printf("+\n");
// 打印位置数组
printf("位置: [");
for (int i = 0; i < N; i++) {
printf("%d%s", solution[i], (i < N - 1) ? ", " : "");
}
printf("]\n");
}
// 打印所有解
void print_all_solutions(int max_display) {
int display = (solution_count < max_display) ? solution_count : max_display;
printf("\n========== 共找到 %d 个解,显示前 %d 个 ==========\n",
solution_count, display);
for (int i = 0; i < display; i++) {
printf("\n---------- 解 #%d ----------", i + 1);
print_board(solutions[i]);
}
if (solution_count > max_display) {
printf("\n... 还有 %d 个解未显示 ...\n", solution_count - max_display);
}
}
// ============ 性能测试 ============
// 测试不同规模的N皇后
void benchmark() {
printf("\n========== N皇后规模测试 ==========\n");
printf("N\t解的数量\t时间(ms)\n");
for (int n = 4; n <= 14; n++) {
int test_board[20] = {0};
int test_count = 0;
clock_t start = clock();
// 使用迭代方式避免递归深度问题
// 这里简化处理,仅测试到N=14
// 临时修改N(实际应使用动态版本)
// 这里仅作演示
clock_t end = clock();
double time_ms = ((double)(end - start)) / CLOCKS_PER_SEC * 1000;
printf("%d\t%d\t\t%.3f\n", n, test_count, time_ms);
}
}
// ============ 主函数 ============
int main() {
int board[N] = {0};
printf("========================================\n");
printf(" 八皇后问题 - C语言实现\n");
printf("========================================\n");
// ===== 版本1:基础回溯(存储所有解)=====
printf("\n【版本1】基础回溯法\n");
clock_t start = clock();
solve_n_queens(board, 0);
clock_t end = clock();
double time_ms = ((double)(end - start)) / CLOCKS_PER_SEC * 1000;
printf("求解完成!找到 %d 个解\n", solution_count);
printf("耗时: %.3f ms\n", time_ms);
// 打印前5个解
print_all_solutions(5);
// ===== 版本2:位运算优化(仅计数)=====
printf("\n========================================\n");
printf("【版本2】位运算优化(仅计数,不存储)\n");
int fast_count = 0;
start = clock();
solve_n_queens_fast(0, 0, 0, 0, &fast_count);
end = clock();
time_ms = ((double)(end - start)) / CLOCKS_PER_SEC * 1000;
printf("求解完成!找到 %d 个解\n", fast_count);
printf("耗时: %.3f ms\n", time_ms);
// ===== 交互式查看 =====
printf("\n========================================\n");
printf("交互模式:输入解的编号查看 (1-%d, 0退出)\n", solution_count);
int choice;
while (1) {
printf("\n请输入编号: ");
if (scanf("%d", &choice) != 1) {
// 清空输入缓冲区
while (getchar() != '\n');
continue;
}
if (choice == 0) break;
if (choice < 1 || choice > solution_count) {
printf("错误:编号超出范围!\n");
continue;
}
printf("\n========== 解 #%d ==========", choice);
print_board(solutions[choice - 1]);
}
printf("\n程序结束!\n");
return 0;
}
输出:
./a.out
========================================
八皇后问题 - C语言实现
========================================
【版本1】基础回溯法
求解完成!找到 92 个解
耗时: 0.336 ms
========== 共找到 92 个解,显示前 5 个 ==========
---------- 解 #1 ----------
0 1 2 3 4 5 6 7
+-----------------+
0 |Q . . . . . . . |
1 |. . . . Q . . . |
2 |. . . . . . . Q |
3 |. . . . . Q . . |
4 |. . Q . . . . . |
5 |. . . . . . Q . |
6 |. Q . . . . . . |
7 |. . . Q . . . . |
+-----------------+
位置: [0, 4, 7, 5, 2, 6, 1, 3]
---------- 解 #2 ----------
0 1 2 3 4 5 6 7
+-----------------+
0 |Q . . . . . . . |
1 |. . . . . Q . . |
2 |. . . . . . . Q |
3 |. . Q . . . . . |
4 |. . . . . . Q . |
5 |. . . Q . . . . |
6 |. Q . . . . . . |
7 |. . . . Q . . . |
+-----------------+
位置: [0, 5, 7, 2, 6, 3, 1, 4]
---------- 解 #3 ----------
0 1 2 3 4 5 6 7
+-----------------+
0 |Q . . . . . . . |
1 |. . . . . . Q . |
2 |. . . Q . . . . |
3 |. . . . . Q . . |
4 |. . . . . . . Q |
5 |. Q . . . . . . |
6 |. . . . Q . . . |
7 |. . Q . . . . . |
+-----------------+
位置: [0, 6, 3, 5, 7, 1, 4, 2]
---------- 解 #4 ----------
0 1 2 3 4 5 6 7
+-----------------+
0 |Q . . . . . . . |
1 |. . . . . . Q . |
2 |. . . . Q . . . |
3 |. . . . . . . Q |
4 |. Q . . . . . . |
5 |. . . Q . . . . |
6 |. . . . . Q . . |
7 |. . Q . . . . . |
+-----------------+
位置: [0, 6, 4, 7, 1, 3, 5, 2]
---------- 解 #5 ----------
0 1 2 3 4 5 6 7
+-----------------+
0 |. Q . . . . . . |
1 |. . . Q . . . . |
2 |. . . . . Q . . |
3 |. . . . . . . Q |
4 |. . Q . . . . . |
5 |Q . . . . . . . |
6 |. . . . . . Q . |
7 |. . . . Q . . . |
+-----------------+
位置: [1, 3, 5, 7, 2, 0, 6, 4]
... 还有 87 个解未显示 ...
========================================
【版本2】位运算优化(仅计数,不存储)
求解完成!找到 92 个解
耗时: 0.029 ms
========================================
交互模式:输入解的编号查看 (1-92, 0退出)
总结
都能完成既定任务,且代码一次性跑通。
先比较而言,模型2的交互更好一些。
总结
经过一年多的发展,大模型对写代码这件事情已经很熟练了。当然对刚出现的新型编程语言,还有点不太适应。
揭晓谜底:
模型1是DeepSeek-R1-0528
模型2是Kimi-k2-0711-preview
感觉模型2 更好一些!但是模型1也是能完成同样的任务的。
更多推荐


所有评论(0)