Files
2026-08-24 04:35:13 +00:00

218 lines
8.9 KiB
HTML
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>062. N 皇后 – 图解</title>
<link rel="stylesheet" href="../shared/style.css">
<style>
/* page-specific overrides */
.vis-area { min-height: 120px; padding: 16px 0; }
.code-section { margin-top: 16px; }
</style>
</head>
<body>
<div class="container">
<h1>🔴 062. N 皇后 <span class="badge hard">困难</span></h1>
<p class="subtitle">分类:回溯 | LeetCode Hot 100</p>
<!-- 控制面板 -->
<div class="controls" id="controls">
<label for="inputArea">输入:</label>
<input type="text" id="inputArea" placeholder="默认示例,可自定义">
<button id="applyBtn" class="primary">生成图解</button>
<select id="exampleSelect"></select>
<span style="flex:1"></span>
<button id="prevBtn">◀ 上一步</button>
<button id="nextBtn">下一步 ▶</button>
<button id="jumpBtn">⏭ 跳到结果</button>
<button id="autoBtn">自动播放</button>
<button id="resetBtn">重置</button>
</div>
<!-- 步骤流水线 -->
<div class="pipeline" id="pipeline"></div>
<!-- 提示条 -->
<div class="hint info" id="hintBox">
<span id="stepInfo"></span><br>
<span id="hintText"></span>
</div>
<!-- 可视化面板 -->
<div class="panels">
<div class="panel" id="mainPanel">
<h3>📊 可视化</h3>
<div class="vis-area" id="vizArea">点击「生成图解」开始</div>
</div>
<div class="panel-grid">
<div class="panel" id="detailPanel">
<h3>📝 当前步骤详情</h3>
<div id="detailContent">等待开始...</div>
</div>
<div class="panel" id="resultPanel">
<h3>✅ 结果</h3>
<div id="resultContent">等待完成...</div>
</div>
</div>
</div>
<!-- 代码 -->
<div class="panel code-section">
<h3>💻 参考代码(Python)</h3>
<div id="codeArea"></div>
</div>
<footer>Powered by QwenPaw · 图解算法 · LeetCode Hot 100</footer>
</div>
<script src="../shared/algo-viz.js"></script>
<script>
"use strict";
(function() {
// ========== Algorithm Logic ==========
const examples = [
{input: 4, label: '示例1: n=4'},
{input: 1, label: '示例2: n=1'},
{input: 6, label: '示例3: n=6'},
];
let n, steps, stepCtrl;
function buildSteps(nn) {
n = nn; steps = [];
const result = [];
const queens = []; // queens[row] = col
steps.push({stage:'start', msg:`${n}皇后问题:逐行放置,检查列和对角线冲突`, queens:[], row:-1, col:-1, result:[]});
function isValid(row, col) {
for (let r = 0; r < queens.length; r++) {
const c = queens[r];
if (c === col || r + c === row + col || r - c === row - col) return false;
}
return true;
}
function backtrack(row) {
if (row === n) {
result.push([...queens]);
const board = queensToBoard(queens);
steps.push({stage:'collect', msg:`找到解!皇后位置: ${queens.map((c,r)=>`(${r},${c})`).join(' ')}`, queens:[...queens], row, col:-1, result:JSON.parse(JSON.stringify(result))});
return;
}
for (let col = 0; col < n; col++) {
const valid = isValid(row, col);
if (valid) {
steps.push({stage:'try_valid', msg:`行${row} 列${col}: 无冲突 ✓,放置皇后`, queens:[...queens], row, col, result:JSON.parse(JSON.stringify(result))});
queens.push(col);
backtrack(row + 1);
queens.pop();
steps.push({stage:'undo', msg:`回溯行${row},移除列${col}皇后`, queens:[...queens], row, col, result:JSON.parse(JSON.stringify(result))});
} else {
steps.push({stage:'conflict', msg:`行${row} 列${col}: 冲突 ✗(列/对角线已有皇后)`, queens:[...queens], row, col, result:JSON.parse(JSON.stringify(result))});
}
}
}
backtrack(0);
steps.push({stage:'done', msg:`共 ${result.length} 个解`, queens:[], row:-1, col:-1, result:JSON.parse(JSON.stringify(result))});
}
function queensToBoard(q) {
return q.map(c => { let row = '.'.repeat(n); return row.substring(0,c) + 'Q' + row.substring(c+1); });
}
function render(step) {
const s = steps[step];
const qSet = new Set(s.queens.map((c,r) => r+','+c));
const tryKey = s.row >= 0 && s.col >= 0 ? s.row+','+s.col : null;
// Build chess board
let viz = `<div style="display:inline-grid;grid-template-columns:repeat(${n},42px);gap:2px;padding:8px;border-radius:8px;background:#1e293b;">`;
for (let r = 0; r < n; r++) {
for (let c = 0; c < n; c++) {
const isQueen = s.queens[r] === c;
const isTry = r === s.row && c === s.col;
const isConflict = isTry && s.stage === 'conflict';
let bg = (r+c) % 2 === 0 ? '#f0f9ff' : '#e0f2fe';
if (isQueen) bg = '#dbeafe';
if (isConflict) bg = '#fee2e2';
else if (isTry && s.stage === 'try_valid') bg = '#fef3c7';
const content = isQueen ? '♛' : '';
const border = isTry ? `2px solid ${isConflict?'var(--red)':'var(--orange)'}` : isQueen ? '2px solid var(--blue)' : '1px solid #94a3b8';
viz += `<div style="width:42px;height:42px;display:flex;align-items:center;justify-content:center;background:${bg};border:${border};border-radius:4px;font-size:20px;cursor:default;${isQueen?'color:var(--blue-dark);font-weight:700;':''}">${content}</div>`;
}
}
viz += '</div>';
// Conflict lines for current try
if (s.stage === 'conflict' && s.row >= 0) {
viz += '<div style="margin-top:8px;color:var(--red);font-size:13px;">';
for (let r=0; r<s.queens.length; r++) {
const c = s.queens[r];
if (c === s.col) viz += `列冲突: 行${r}列${c} ↔ 行${s.row}列${s.col} `;
if (r+c === s.row+s.col) viz += `↗对角线冲突: (${r},${c}) ↔ (${s.row},${s.col}) `;
if (r-c === s.row-s.col) viz += `↘对角线冲突: (${r},${c}) ↔ (${s.row},${s.col}) `;
}
viz += '</div>';
}
viz += `<div style="margin-top:8px;"><b>当前放置:</b> ${s.queens.length > 0 ? s.queens.map((c,r)=>`行${r}=列${c}`).join(', ') : '无'}</div>`;
if (s.result.length > 0) {
viz += `<div style="margin-top:8px;"><b>已找到 ${s.result.length} 个解</b></div>`;
}
$('vizArea').innerHTML = viz;
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
if (s.stage==='done') $('resultContent').innerHTML = `<div class="final-answer">共 <b>${s.result.length}</b> 个解</div>`;
$('hintText').textContent = s.msg;
const stages = ['start→开始','try_valid→尝试放置','conflict→冲突','collect→收集解','undo→回溯','done→完成'];
$('pipeline').innerHTML = stages.map(st => { const [k,l]=st.split('→'); return `<span class="pipe-step ${s.stage===k?'active':''}">${l}</span>`; }).join('<i>→</i>');
}
function init() {
const sel = $('exampleSelect');
examples.forEach((e,i) => { sel.innerHTML += `<option value="${i}">${e.label}</option>`; });
$('inputArea').value = '4';
buildSteps(examples[0].input);
stepCtrl = new StepController({onStep: render});
stepCtrl.setSteps(steps.map((_,i)=>i));
$('stepInfo').textContent = '步骤 1 / ' + steps.length;
stepCtrl.onStep = (idx) => { render(idx); $('stepInfo').textContent = `步骤 ${idx+1} / ${steps.length}`; };
$('applyBtn').onclick = () => {
const v = parseInt($('inputArea').value);
if (isNaN(v)||v<1||v>8) { alert('请输入1-8的整数(8以上步骤过多)'); return; }
buildSteps(v); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0); $('stepInfo').textContent = '步骤 1 / ' + steps.length;
};
$('exampleSelect').onchange = () => {
const e = examples[parseInt($('exampleSelect').value)];
buildSteps(e.input); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0);
};
$('prevBtn').onclick = () => stepCtrl.prev();
$('nextBtn').onclick = () => stepCtrl.next();
$('jumpBtn').onclick = () => stepCtrl.jumpToEnd();
$('autoBtn').onclick = () => { const on = stepCtrl.toggleAuto(); $('autoBtn').textContent = on ? '暂停' : '自动播放'; };
$('resetBtn').onclick = () => { stepCtrl.reset(); $('autoBtn').textContent = '自动播放'; };
}
init();
$('codeArea').innerHTML = renderCode(`def solveNQueens(n):
res = []
def backtrack(row, queens):
if row == n:
res.append(queens[:])
return
for col in range(n):
valid = True
for r, c in enumerate(queens):
if c == col or r+c == row+col or r-c == row-col:
valid = False; break
if valid:
queens.append(col)
backtrack(row + 1, queens)
queens.pop()
backtrack(0, [])
return [['.'*c + 'Q' + '.'*(n-c-1) for c in sol] for sol in res]`, {lang:'Python'});
})();
</script>
</body>
</html>