Files
illustrated-algorithm/word-search/index.html
T
2026-08-24 04:35:13 +00:00

206 lines
8.5 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
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>060. 单词搜索 – 图解</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>🟡 060. 单词搜索 <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 = [
{board: [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word: "ABCCED", label: '示例1: ABCCED'},
{board: [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word: "SEE", label: '示例2: SEE'},
{board: [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word: "ABCB", label: '示例3: ABCB(不存在)'},
];
let board, word, R, C, steps, stepCtrl;
function buildSteps(b, w) {
board = b.map(r=>[...r]); R = board.length; C = board[0].length; word = w;
steps = [];
let found = false;
steps.push({stage:'start', msg:`在网格中搜索单词 "${word}"`, hl:{}, path:[], charIdx:0, found:false});
function dfs(r, c, idx, path, visited) {
if (idx === word.length) {
found = true;
steps.push({stage:'found', msg:`找到单词 "${word}"!`, hl:{}, path:[...path], charIdx:idx, found:true});
return true;
}
if (r<0||r>=R||c<0||c>=C||visited.has(r+','+c)||board[r][c]!==word[idx]) {
if (r>=0&&r<R&&c>=0&&c<C&&board[r][c]!==word[idx])
steps.push({stage:'mismatch', msg:`(${r},${c})='${board[r][c]}' ≠ '${word[idx]}',跳过`, hl:{[r+','+c]:'wall'}, path:[...path], charIdx:idx, found:false});
return false;
}
visited.add(r+','+c);
path.push(r+','+c);
const hl = {}; hl[r+','+c] = 'current';
// show visited cells
visited.forEach(k => { if(k!==r+','+c) hl[k]='visited'; });
steps.push({stage:'match', msg:`(${r},${c})='${board[r][c]}' = '${word[idx]}' 匹配 ✓ (第${idx+1}/${word.length}个)`, hl, path:[...path], charIdx:idx+1, found:false});
const dirs = [[0,1],[0,-1],[1,0],[-1,0]];
for (const [dr,dc] of dirs) {
if (dfs(r+dr, c+dc, idx+1, path, visited)) return true;
}
visited.delete(r+','+c);
path.pop();
steps.push({stage:'backtrack', msg:`从 (${r},${c}) 回溯`, hl:{}, path:[...path], charIdx:idx, found:false});
return false;
}
for (let r=0; r<R && !found; r++) {
for (let c=0; c<C && !found; c++) {
if (board[r][c] === word[0]) {
const hl = {}; hl[r+','+c] = 'current';
steps.push({stage:'start_pos', msg:`找到起始点 (${r},${c})='${word[0]}'`, hl, path:[], charIdx:0, found:false});
const path = [];
const visited = new Set();
dfs(r, c, 0, path, visited);
}
}
}
if (!found) steps.push({stage:'not_found', msg:`未找到单词 "${word}"`, hl:{}, path:[], charIdx:-1, found:false});
}
function render(step) {
const s = steps[step];
const cellStyle = (val,r,c) => {
const key = r+','+c;
if (s.hl[key]==='current') return 'background:#fef3c7;border-color:var(--orange);box-shadow:0 0 0 3px rgba(245,158,11,0.3);color:#92400e;font-weight:700;';
if (s.hl[key]==='visited') return 'background:#dcfce7;border-color:var(--green);color:#166534;';
if (s.hl[key]==='wall') return 'background:#fee2e2;color:#991b1b;';
return 'background:white;color:var(--text);';
};
let viz = renderGrid(board, {highlights:s.hl, cellSize:48, cellStyle});
viz += `<div style="margin-top:8px;"><b>搜索词:</b>`;
for (let i=0; i<word.length; i++) {
const matched = i < s.charIdx;
viz += `<span style="font-weight:700;font-size:16px;color:${matched?'var(--green)':'var(--text-muted)'};${i===s.charIdx?'text-decoration:underline;':''}">${word[i]}</span>`;
}
viz += '</div>';
if (s.path.length > 0) viz += `<div style="margin-top:4px;">路径: ${s.path.map(p=>'('+p+')').join(' → ')}</div>`;
$('vizArea').innerHTML = viz;
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
if (s.stage==='found') $('resultContent').innerHTML = `<div class="final-answer">返回 <b>True</b>,路径: ${s.path.map(p=>'('+p+')').join('→')}</div>`;
if (s.stage==='not_found') $('resultContent').innerHTML = '<div class="final-answer" style="border-color:#f87171;background:#fef2f2;">返回 <b>False</b></div>';
$('hintText').textContent = s.msg;
const stages = ['start→开始','start_pos→起始点','match→匹配','mismatch→不匹配','backtrack→回溯','found→找到','not_found→未找到'];
$('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 = 'ABCCED';
buildSteps(examples[0].board, examples[0].word);
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 = () => {
buildSteps(examples[0].board, $('inputArea').value.trim());
stepCtrl.setSteps(steps.map((_,i)=>i)); render(0); $('stepInfo').textContent = '步骤 1 / ' + steps.length;
};
$('exampleSelect').onchange = () => {
const e = examples[parseInt($('exampleSelect').value)];
buildSteps(e.board, e.word); 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 exist(board, word):
rows, cols = len(board), len(board[0])
def dfs(r, c, idx, visited):
if idx == len(word):
return True
if (r<0 or r>=rows or c<0 or c>=cols
or (r,c) in visited or board[r][c]!=word[idx]):
return False
visited.add((r, c))
for dr, dc in [(0,1),(0,-1),(1,0),(-1,0)]:
if dfs(r+dr, c+dc, idx+1, visited):
return True
visited.remove((r, c))
return False
for r in range(rows):
for c in range(cols):
if dfs(r, c, 0, set()):
return True
return False`, {lang:'Python'});
})();
</script>
</body>
</html>