Files

190 lines
8.0 KiB
HTML
Raw Permalink Normal View History

<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>083. 打家劫舍 – 图解</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>🟡 083. 打家劫舍 <span class="badge medium">中等</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: [1,2,3,1], label: '示例1: [1,2,3,1]'},
{input: [2,7,9,3,1], label: '示例2: [2,7,9,3,1]'},
{input: [2,1,1,2], label: '示例3: [2,1,1,2]'},
];
let nums, steps, stepCtrl;
function buildSteps(arr) {
nums = [...arr]; steps = [];
const n = nums.length;
if (n === 0) { steps.push({stage:'done', msg:'数组为空', dp:[], rob:[]}); return; }
const dp = new Array(n).fill(0);
const rob = new Array(n).fill(false);
dp[0] = nums[0]; rob[0] = true;
steps.push({stage:'init', msg:`dp[0] = ${nums[0]}(只有一间房子,必须偷)`, dp:[...dp], rob:[...rob], current:0, choice:null});
if (n > 1) {
if (nums[1] > nums[0]) { dp[1] = nums[1]; rob[1] = true; rob[0] = false; }
else { dp[1] = nums[0]; rob[1] = false; }
steps.push({stage:'init2', msg:`dp[1] = max(${nums[0]}, ${nums[1]}) = ${dp[1]}`, dp:[...dp], rob:[...rob], current:1, choice:'max'});
}
for (let i = 2; i < n; i++) {
const notRob = dp[i-1];
const doRob = dp[i-2] + nums[i];
steps.push({stage:'compare', msg:`dp[${i}]:不偷 = dp[${i-1}] = ${notRob},偷 = dp[${i-2}] + nums[${i}] = ${dp[i-2]} + ${nums[i]} = ${doRob}`, dp:[...dp], rob:[...rob], current:i, choice:'comparing', notRob, doRob});
if (doRob > notRob) {
dp[i] = doRob; rob[i] = true;
steps.push({stage:'rob', msg:`偷第 ${i} 间更优:dp[${i}] = ${doRob}`, dp:[...dp], rob:[...rob], current:i, choice:'rob'});
} else {
dp[i] = notRob; rob[i] = false;
steps.push({stage:'skip', msg:`不偷第 ${i} 间更优:dp[${i}] = ${notRob}`, dp:[...dp], rob:[...rob], current:i, choice:'skip'});
}
}
steps.push({stage:'done', msg:`最多可以偷取 ${dp[n-1]}`, dp:[...dp], rob:[...rob], current:n-1, choice:'done'});
}
function render(step) {
const s = steps[step];
let viz = '<div style="display:flex;gap:6px;margin:8px 0;">';
nums.forEach((v, i) => {
const isCurrent = i === s.current && s.stage !== 'done';
const isRobbed = s.rob[i];
let bg = '#e2e8f0', color = '#475569', border = '2px solid #cbd5e1';
if (isRobbed && s.stage === 'done') { bg = '#dcfce7'; color = '#166534'; border = '2px solid #16a34a'; }
else if (isCurrent && s.choice === 'rob') { bg = '#fef3c7'; color = '#92400e'; border = '2px solid #f59e0b'; }
else if (isCurrent) { bg = '#dbeafe'; color = '#1e40af'; border = '2px solid #3b82f6'; }
else if (isRobbed) { bg = '#dcfce7'; color = '#166534'; border = '2px solid #86efac'; }
viz += `<div style="width:56px;padding:8px 4px;background:${bg};border:${border};border-radius:10px;text-align:center;font-size:13px;font-weight:600;color:${color};transition:all 0.3s;">
<div style="font-size:16px;margin-bottom:2px;">🏠</div>
<div>${v}</div>
<div style="font-size:10px;color:${isRobbed?'#16a34a':'#94a3b8'};">${isRobbed?'偷':'·'}</div>
</div>`;
});
viz += '</div>';
viz += '<div style="margin-top:12px;"><b>dp 值:</b></div>';
const dpHl = {};
if (s.current >= 0) dpHl[s.current] = s.choice==='rob'?'orange':'blue';
viz += renderArray(s.dp, {highlights: dpHl});
if (s.stage === 'compare') {
viz += `<div class="formula-box" style="margin-top:8px;">dp[${s.current}] = max(不偷=${s.notRob}, 偷=${s.doRob})</div>`;
}
$('vizArea').innerHTML = viz;
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
if (s.dp.length > 0) {
$('detailContent').innerHTML += `<div class="current-answer">当前最大金额:<b>${s.dp[Math.max(0,s.current)]}</b></div>`;
}
if (s.stage === 'done') {
$('resultContent').innerHTML = `<div class="final-answer">最多可以偷取 <b>${s.dp[nums.length-1]}</b></div>`;
}
$('hintText').textContent = s.msg;
const stages = ['init→初始化','init2→初始化','compare→比较','rob→偷','skip→不偷','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 = '[1,2,3,1]';
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 = () => {
try { const arr = JSON.parse($('inputArea').value); buildSteps(arr); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0); $('stepInfo').textContent = '步骤 1 / ' + steps.length; }
catch(e) { alert('请输入合法 JSON 数组'); }
};
$('exampleSelect').onchange = () => {
const e = examples[parseInt($('exampleSelect').value)];
$('inputArea').value = JSON.stringify(e.input);
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 rob(nums):
n = len(nums)
if n == 0: return 0
if n == 1: return nums[0]
dp = [0] * n
dp[0], dp[1] = nums[0], max(nums[0], nums[1])
for i in range(2, n):
dp[i] = max(dp[i-1], dp[i-2] + nums[i])
return dp[-1]`, {lang:'Python'});
})();
</script>
</body>
</html>