200 lines
8.4 KiB
HTML
200 lines
8.4 KiB
HTML
|
|
<!DOCTYPE html>
|
|||
|
|
<html lang="zh-Hans">
|
|||
|
|
<head>
|
|||
|
|
<meta charset="UTF-8">
|
|||
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|||
|
|
<title>051. 岛屿数量 – 图解</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>🟡 051. 岛屿数量 <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 = [
|
|||
|
|
{grid: [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]], label: '示例1: 4×5 3个岛'},
|
|||
|
|
{grid: [["1","1","1"],["0","1","0"],["1","1","1"]], label: '示例2: 3×3 1个岛'},
|
|||
|
|
];
|
|||
|
|
let grid, R, C, steps, stepCtrl, islandColors, finalMap;
|
|||
|
|
|
|||
|
|
function buildSteps(g) {
|
|||
|
|
grid = g.map(r=>[...r]); R = grid.length; C = grid[0].length;
|
|||
|
|
steps = []; islandColors = {}; finalMap = {};
|
|||
|
|
const visited = Array.from({length:R},()=>Array(C).fill(false));
|
|||
|
|
let islands = 0;
|
|||
|
|
const islandColorList = ['blue','green','purple','orange','cyan','red'];
|
|||
|
|
|
|||
|
|
steps.push({stage:'start', msg:'遍历网格,遇到未访问的陆地进行DFS染色', hl:{}, im:{}, islands:0});
|
|||
|
|
|
|||
|
|
for (let r=0; r<R; r++) {
|
|||
|
|
for (let c=0; c<C; c++) {
|
|||
|
|
if (grid[r][c]==='1' && !visited[r][c]) {
|
|||
|
|
islands++;
|
|||
|
|
const color = islandColorList[(islands-1) % islandColorList.length];
|
|||
|
|
islandColors[islands] = color;
|
|||
|
|
steps.push({stage:'new_island', msg:`发现岛屿 #${islands},从 (${r},${c}) 开始DFS`, hl:{[r+','+c]:'current'}, im:JSON.parse(JSON.stringify(finalMap)), islands});
|
|||
|
|
|
|||
|
|
const stack = [[r,c]];
|
|||
|
|
visited[r][c] = true;
|
|||
|
|
finalMap[r+','+c] = islands;
|
|||
|
|
|
|||
|
|
while (stack.length > 0) {
|
|||
|
|
const [cr, cc] = stack.pop();
|
|||
|
|
const dirs = [[0,1],[0,-1],[1,0],[-1,0]];
|
|||
|
|
for (const [dr,dc] of dirs) {
|
|||
|
|
const nr=cr+dr, nc=cc+dc;
|
|||
|
|
if (nr>=0 && nr<R && nc>=0 && nc<C && grid[nr][nc]==='1' && !visited[nr][nc]) {
|
|||
|
|
visited[nr][nc] = true;
|
|||
|
|
stack.push([nr,nc]);
|
|||
|
|
finalMap[nr+','+nc] = islands;
|
|||
|
|
const hl2 = {}; hl2[nr+','+nc] = 'current';
|
|||
|
|
steps.push({stage:'dfs', msg:`DFS: (${cr},${cc}) → (${nr},${nc}) 染色为岛 #${islands}`, hl:hl2, im:JSON.parse(JSON.stringify(finalMap)), islands});
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
steps.push({stage:'island_done', msg:`岛屿 #${islands} DFS完成`, hl:{}, im:JSON.parse(JSON.stringify(finalMap)), islands});
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
steps.push({stage:'done', msg:`遍历完毕,共 ${islands} 个岛屿`, hl:{}, im:JSON.parse(JSON.stringify(finalMap)), islands});
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function render(step) {
|
|||
|
|
const s = steps[step];
|
|||
|
|
const cellClass = (val,r,c) => {
|
|||
|
|
if (val==='0') return 'water';
|
|||
|
|
const key = r+','+c;
|
|||
|
|
const iid = s.im[key];
|
|||
|
|
if (iid) return islandColors[iid] || 'island';
|
|||
|
|
return 'default';
|
|||
|
|
};
|
|||
|
|
const cellStyle = (val,r,c) => {
|
|||
|
|
if (val==='0') return 'background:#e0f2fe;color:#0369a1;';
|
|||
|
|
const key = r+','+c;
|
|||
|
|
const iid = s.im[key];
|
|||
|
|
const colorMap = {blue:'background:#dbeafe;color:#1e40af;',green:'background:#dcfce7;color:#166534;',purple:'background:#ede9fe;color:#5b21b6;',orange:'background:#fff7ed;color:#9a3412;',cyan:'background:#cffafe;color:#155e75;',red:'background:#fee2e2;color:#991b1b;'};
|
|||
|
|
if (iid && colorMap[islandColors[iid]]) return colorMap[islandColors[iid]];
|
|||
|
|
return 'background:#f1f5f9;color:#475569;';
|
|||
|
|
};
|
|||
|
|
let viz = renderGrid(grid, {highlights:s.hl, cellSize:48, cellClass, cellStyle});
|
|||
|
|
viz += `<div style="margin-top:8px;">🏝️ 岛屿数量:${s.islands}</div>`;
|
|||
|
|
$('vizArea').innerHTML = viz;
|
|||
|
|
$('detailContent').innerHTML = '<div class="calc-block">' + s.msg + '</div>';
|
|||
|
|
if (s.stage==='done') {
|
|||
|
|
let det = `<div class="final-answer">岛屿数量 = <b>${s.islands}</b></div>`;
|
|||
|
|
det += '<div style="margin-top:8px;">';
|
|||
|
|
for (let i=1; i<=s.islands; i++) det += `<span style="margin-right:12px;"><span style="display:inline-block;width:14px;height:14px;border-radius:3px;${islandColors[i]==='blue'?'background:#dbeafe':islandColors[i]==='green'?'background:#dcfce7':islandColors[i]==='purple'?'background:#ede9fe':'background:#fff7ed'};vertical-align:middle;"></span> 岛屿 #${i}</span>`;
|
|||
|
|
det += '</div>';
|
|||
|
|
$('resultContent').innerHTML = det;
|
|||
|
|
}
|
|||
|
|
$('hintText').textContent = s.msg;
|
|||
|
|
const stages = ['start→开始','new_island→发现岛屿','dfs→DFS染色','island_done→岛屿完成','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","1","0"],["0","1","0"],["0","0","1"]]';
|
|||
|
|
buildSteps(examples[0].grid);
|
|||
|
|
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 g = JSON.parse($('inputArea').value); buildSteps(g); 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)];
|
|||
|
|
buildSteps(e.grid); 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 numIslands(grid):
|
|||
|
|
if not grid: return 0
|
|||
|
|
rows, cols = len(grid), len(grid[0])
|
|||
|
|
def dfs(r, c):
|
|||
|
|
if r<0 or r>=rows or c<0 or c>=cols or grid[r][c]!='1':
|
|||
|
|
return
|
|||
|
|
grid[r][c] = '2'
|
|||
|
|
dfs(r+1,c); dfs(r-1,c)
|
|||
|
|
dfs(r,c+1); dfs(r,c-1)
|
|||
|
|
islands = 0
|
|||
|
|
for r in range(rows):
|
|||
|
|
for c in range(cols):
|
|||
|
|
if grid[r][c] == '1':
|
|||
|
|
islands += 1
|
|||
|
|
dfs(r, c)
|
|||
|
|
return islands`, {lang:'Python'});
|
|||
|
|
|
|||
|
|
})();
|
|||
|
|
</script>
|
|||
|
|
</body>
|
|||
|
|
</html>
|