import React, { useState } from 'react'; import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'; import { generateNQueensCase, solveNQueensCase, runNQueensBenchmark } from '../api'; const NQueens = () => { const [n, setN] = useState(8); const [currentSolution, setCurrentSolution] = useState(null); const [solutionCount, setSolutionCount] = useState(null); const [solveTime, setSolveTime] = useState(null); const [benchmarkResults, setBenchmarkResults] = useState(null); const [loading, setLoading] = useState(false); const handleSolve = async () => { setLoading(true); try { // Generate is trivial (just N), so we skip explicit generate step for UI simplicity // and just call solve directly const results = await solveNQueensCase(n, ["backtracking"]); if (results && results.length > 0) { const res = results[0]; setCurrentSolution(res.first_solution); setSolutionCount(res.solution_count); setSolveTime(res.time_seconds); } } catch (error) { console.error("Error solving N-Queens:", error); alert("求解失败"); } setLoading(false); }; const handleBenchmark = async () => { setLoading(true); try { const sizes = [4, 8, 10, 12, 13]; const results = await runNQueensBenchmark(sizes, ["backtracking"]); const chartData = results.map(item => { const point = { size: item.size }; item.algorithms.forEach(algo => { if (algo.time_seconds !== undefined && algo.time_seconds !== null) { point[algo.algorithm] = algo.time_seconds; } }); return point; }); setBenchmarkResults(chartData); } catch (error) { console.error("Error running benchmark:", error); alert("性能测试失败"); } setLoading(false); }; // Render the chess board const renderBoard = () => { if (!currentSolution) return null; const boardSize = 400; const cellSize = boardSize / n; return (
目标:在 N×N 的棋盘上放置 N 个皇后,使得它们互不攻击。
建议 N ≤ 14,否则计算时间过长
找到解的数量: {solutionCount}
耗时: {solveTime?.toFixed(6)} 秒
点击求解以查看结果