版本比较
图-查看器
正文
增加 274 行删除 61 行
87 行未改动888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149154 行未改动全部展开30430530630730830931031131231331431531631731831932032132232332432517 行未改动34334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139285 行未改动47847948048148248348448548648748814 行未改动5035045055064025075085095105115125135145153 行未改动51952052152252352452552652752852953053153253310 行未改动5445455465475485495505515525535545555565578 行未改动5665675685694505705715725735744565755765775782 行未改动5815825835844675855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526534726546556566576 行未改动66466566666748766866967067167249367367467567611 行未改动6886896906915136926936946955 行未改动7017027037045277057067077083 行未改动7127137147155395405417167177187197207217226 行未改动729730731732556557558559560733734735736737738739740741567742743744571745746747748749750751752753581754755756757586758759760761114 行未改动全部展开87687787887970971071171288088188271688388488588672188788888989035 行未改动92692792892976593093193293393493593677393793893994077894194294394416 行未改动96196296396480396596696796896997081097197297397497542 行未改动10181019102010218611022102310241025102610271028102910308711031103210331034127 行未改动全部展开11621163116411651007116611671168116911709 行未改动1180118111821183102511841185118611876 行未改动1194119511961197104011981199120012015 行未改动1207120812091210105410551056121112121059121312141215106212161217121812195 行未改动12251226122712281076122912301231123216 行未改动12491250125112521101125312541255110512561257125812595 行未改动12651266126712681119126912701271127269 行未改动134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422120214231424142514262 行未改动14291430143114321433143414351436143716 行未改动145414551456145712371458145914601461187 行未改动全部展开1649165016511652143316531654165516566 行未改动166316641665166614481667166816691670167171 行未改动17431744174517461528174717481749175020 行未改动1771177217731774155717751776177717781779178017811782178315671784178517861787178844 行未改动183318341835183616201837183818391840184184 行未改动192619271928192917131930193119321933142 行未改动全部展开207620772078207918642080208120822083208461 行未改动214621472148214919342150215121522153215430 行未改动218521862187218819732189219021912192133 行未改动全部展开2326232723282329211523302331233223332120233423352336233799 行未改动243724382439244022282441244224432444118 行未改动全部展开2563256425652566256725682569257025712 行未改动87 行未改动 .btn-row .btn{margin-top:0;}
.hint{font-size:12px;color:var(--muted);line-height:1.6;margin:9px 0 0;}
/* ================= 滑块 ================= */ .slider-row{margin-bottom:14px;} .slider-row:last-of-type{margin-bottom:0;} .slider-row label{ display:flex;justify-content:space-between;align-items:center; font-size:12.5px;color:#334155;margin-bottom:6px;gap:8px; } .slider-row label .name{font-weight:500;} .slider-row label .val{ font-family:ui-monospace,Menlo,monospace;font-size:12px; color:var(--primary);font-weight:700;background:#eff6ff; padding:1px 8px;border-radius:5px;min-width:52px;text-align:center; } .slider-row input[type=range]{ width:100%;height:5px;border-radius:3px; background:#e2e8f0;outline:none;-webkit-appearance:none; appearance:none;cursor:pointer;padding:0;margin:0; } .slider-row input[type=range]::-webkit-slider-thumb{ -webkit-appearance:none;appearance:none; width:16px;height:16px;border-radius:50%; background:var(--primary);cursor:pointer; border:2px solid #fff;box-shadow:0 1px 4px rgba(37,99,235,.45); transition:transform .12s ease; } .slider-row input[type=range]::-webkit-slider-thumb:hover{ transform:scale(1.15); } .slider-row input[type=range]::-webkit-slider-thumb:active{ transform:scale(1.25); } .slider-row input[type=range]::-moz-range-thumb{ width:14px;height:14px;border-radius:50%; background:var(--primary);cursor:pointer; border:2px solid #fff;box-shadow:0 1px 4px rgba(37,99,235,.45); } .slider-row input[type=range]::-moz-range-track{ height:5px;border-radius:3px;background:#e2e8f0; } .slider-row .desc{ font-size:11px;color:#94a3b8;margin-top:5px;line-height:1.4; }
.code-area{ width:100%;min-height:180px;padding:10px 12px;margin-top:8px; border:1px solid #cbd5e1;border-radius:9px;background:#0f172a;color:#e2e8f0; font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:12.5px;line-height:1.6;outline:none;resize:vertical; transition:.15s; } .code-area:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.15);} .code-area[readonly]{ background:#0b1220;cursor:text; } .code-status{font-size:12px;margin-top:8px;line-height:1.5;min-height:17px;color:var(--muted);} .code-status.err{color:#b91c1c;font-weight:600;} .code-status.ok{color:#15803d;font-weight:600;}
154 行未改动全部展开 <p class="code-status" id="codeStatus"></p> </div> </details>
<details class="card" id="exportCard"> <summary>📤 数据导出</summary> <div> <div style="font-size:12px;color:#64748b;line-height:1.7;background:#eef2f7;border-radius:8px;padding:8px 10px;"> 当前图的文本表示,可直接复制粘贴回代码模式,或保存到本地。<br> <span style="color:#94a3b8">启用容量时导出 u v w,否则导出 u v。</span> </div> <textarea id="exportArea" class="code-area" readonly spellcheck="false" style="min-height:160px;background:#0b1220;"></textarea> <button class="btn primary" id="btnExportCopy" style="margin-top:8px">📋 复制到剪贴板</button> <p class="code-status" id="exportStatus"></p> </div> </details>
<section class="card"> <h2>参数</h2> <label class="row"><span>顶点数 n</span> <input type="number" id="numNodes" min="0" max="60" value="7" step="1">17 行未改动 <label class="check"><input type="checkbox" id="chkPhysics" checked> 弹性碰撞箱(解压手感)</label> <p class="hint">开启后顶点互相碰撞、拖拽带惯性;关闭后顶点静止且可自由重叠。</p> </section>
<section class="card" id="physTuningCard"> <h2>物理调参</h2>
<div class="slider-row"> <label> <span class="name">速度阻尼(阻力)</span> <span class="val" id="dampingVal">0.925</span> </label> <input type="range" id="dampingSlider" min="0.5" max="1" step="0.005" value="0.925"> <div class="desc">每帧速度保留比例。越小阻力越大,顶点越快停下;越大越顺滑。</div> </div>
<div class="slider-row"> <label> <span class="name">拖拽阻尼</span> <span class="val" id="dragDragVal">0.88</span> </label> <input type="range" id="dragDragSlider" min="0.3" max="1" step="0.01" value="0.88"> <div class="desc">拖动顶点时速度衰减。越小拖动越稳,越大松手飞得越远。</div> </div>
<div class="slider-row"> <label> <span class="name">碰撞弹性</span> <span class="val" id="restitutionVal">0.78</span> </label> <input type="range" id="restitutionSlider" min="0" max="1" step="0.02" value="0.78"> <div class="desc">两顶点碰撞后能量保留比例。0 = 完全非弹性,1 = 完全弹性。</div> </div>
<div class="slider-row"> <label> <span class="name">撞墙弹性</span> <span class="val" id="wallBounceVal">0.62</span> </label> <input type="range" id="wallBounceSlider" min="0" max="1" step="0.02" value="0.62"> <div class="desc">撞到画布边界时能量保留比例。</div> </div>
<button class="btn" id="btnPhysReset" style="margin-top:10px">↻ 恢复默认</button> </section>
<section class="card"> <h2>编辑模式</h2> <div class="seg" id="modeSeg"> <button class="seg-btn active" data-mode="drag">拖动</button>85 行未改动 const popupHeader= document.getElementById('popupHeader'); const popupCapInput = document.getElementById('popupCapInput'); const codeInput = document.getElementById('codeInput'); const codeStatus = document.getElementById('codeStatus'); const exportArea = document.getElementById('exportArea'); const exportStatus = document.getElementById('exportStatus'); const exportCard = document.getElementById('exportCard');
let W = 900, H = 650;
let nodes = [];14 行未改动 let highlight = { nodeIds: new Set(), edgeIds: new Set() }; let topoColorMap = new Map(); let flowHighlight = new Map();
/* 每条边的几何元数据:{offset, selfIdx, selfTotal} */ let edgeMeta = new Map();
/* ============================================================ * 物理参数(可通过滑块调整) * ============================================================ */ const PHYS = { restitution: 0.78, damping: 0.925, wallBounce: 0.62,3 行未改动 sleepSpeed: 0.075, iterations: 2 };
const PHYS_DEFAULTS = { restitution: 0.78, damping: 0.925, wallBounce: 0.62, dragDrag: 0.88, };
let physicsEnabled = chkPhysics.checked; let physicsOn = false; let lastFrame = 0;
10 行未改动 const s = v.toFixed(4).replace(/0+$/, '').replace(/\.$/, ''); return s || '0'; }
function fullNumStr(v) { if (typeof v !== 'number' || !Number.isFinite(v)) return '1'; if (Number.isInteger(v)) return String(v); return String(v); }
function shuffle(arr) { for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]];8 行未改动 y: (e.clientY - r.top ) * (H / (r.height || H)) }; }
/* 边的有效容量 */ function edgeCap(e) { if (!capEnabled) return 1; return (typeof e.cap === 'number' && Number.isFinite(e.cap)) ? e.cap : 1; }
/* 是否为负权边 */ function isNegEdge(e) { return directed && capEnabled && typeof e.cap === 'number' && e.cap < 0; }
2 行未改动 function clearFlow() { flowHighlight = new Map(); } function clearAllVisual() { clearHighlight(); clearTopo(); clearFlow(); closePopup(); }
/* ============================================================ * 边几何:元数据计算(偏移 / 自环索引) * 物理调参滑块 * ============================================================ */ const dampingSlider = document.getElementById('dampingSlider'); const dampingVal = document.getElementById('dampingVal'); const dragDragSlider= document.getElementById('dragDragSlider'); const dragDragVal = document.getElementById('dragDragVal'); const restitutionSlider = document.getElementById('restitutionSlider'); const restitutionVal = document.getElementById('restitutionVal'); const wallBounceSlider = document.getElementById('wallBounceSlider'); const wallBounceVal = document.getElementById('wallBounceVal');
function syncPhysSliders() { dampingSlider.value = PHYS.damping; dampingVal.textContent = PHYS.damping.toFixed(3);
dragDragSlider.value = PHYS.dragDrag; dragDragVal.textContent = PHYS.dragDrag.toFixed(2);
restitutionSlider.value = PHYS.restitution; restitutionVal.textContent = PHYS.restitution.toFixed(2);
wallBounceSlider.value = PHYS.wallBounce; wallBounceVal.textContent = PHYS.wallBounce.toFixed(2); }
dampingSlider.addEventListener('input', () => { PHYS.damping = parseFloat(dampingSlider.value); dampingVal.textContent = PHYS.damping.toFixed(3); wake(); });
dragDragSlider.addEventListener('input', () => { PHYS.dragDrag = parseFloat(dragDragSlider.value); dragDragVal.textContent = PHYS.dragDrag.toFixed(2); wake(); });
restitutionSlider.addEventListener('input', () => { PHYS.restitution = parseFloat(restitutionSlider.value); restitutionVal.textContent = PHYS.restitution.toFixed(2); wake(); });
wallBounceSlider.addEventListener('input', () => { PHYS.wallBounce = parseFloat(wallBounceSlider.value); wallBounceVal.textContent = PHYS.wallBounce.toFixed(2); wake(); });
document.getElementById('btnPhysReset').addEventListener('click', () => { Object.assign(PHYS, PHYS_DEFAULTS); syncPhysSliders(); wake(); });
/* ============================================================ * 边几何 * ============================================================ */ function canonicalPerp(A, B) { const dx = B.x - A.x, dy = B.y - A.y; const d = Math.hypot(dx, dy) || 1; const ux = dx / d, uy = dy / d; const sign = A.id < B.id ? 1 : -1; return { x: -uy * sign, y: ux * sign }; }
function computeEdgeMeta() { edgeMeta = new Map();
/* 非自环:按无序节点对分组 */ const groups = new Map(); for (const e of edges) { if (e.a === e.b) continue; const key = Math.min(e.a, e.b) + '-' + Math.max(e.a, e.b);6 行未改动 edgeMeta.set(group[0].id, { offset: 0 }); continue; } if (!directed) { /* 无向图:均匀扇开 */ const total = group.length; group.forEach((e, i) => { edgeMeta.set(e.id, { offset: (i - (total - 1) / 2) * 30 }); }); } else { /* 有向图:按方向分开 */ const minId = Number(key.split('-')[0]); const forward = group.filter(e => e.a === minId); const backward = group.filter(e => e.a !== minId); const hasF = forward.length > 0;11 行未改动 } } }
/* 自环:按节点分组 */ const selfGroups = new Map(); for (const e of edges) { if (e.a !== e.b) continue; if (!selfGroups.has(e.a)) selfGroups.set(e.a, []);5 行未改动 }); } }
/* 直线 / 弯曲边路径 */ function edgePath(A, B, offset) { const dx = B.x - A.x, dy = B.y - A.y; const d = Math.hypot(dx, dy) || 1; const ux = dx / d, uy = dy / d;3 行未改动 if (Math.abs(offset) < 1) { return `M ${A.x + ux * r1} ${A.y + uy * r1} L ${B.x - ux * r2} ${B.y - uy * r2}`; }
const px = -uy, py = ux; const cx = (A.x + B.x) / 2 + px * offset; const cy = (A.y + B.y) / 2 + py * offset; const perp = canonicalPerp(A, B); const cx = (A.x + B.x) / 2 + perp.x * offset; const cy = (A.y + B.y) / 2 + perp.y * offset;
const sdx = cx - A.x, sdy = cy - A.y, sd = Math.hypot(sdx, sdy) || 1; const sx = A.x + sdx / sd * r1, sy = A.y + sdy / sd * r1;
6 行未改动 function edgeMidpoint(A, B, offset) { if (Math.abs(offset) < 1) { return { x: (A.x + B.x) / 2, y: (A.y + B.y) / 2 }; } const dx = B.x - A.x, dy = B.y - A.y; const d = Math.hypot(dx, dy) || 1; const px = -dy / d, py = dx / d; const cx = (A.x + B.x) / 2 + px * offset; const cy = (A.y + B.y) / 2 + py * offset; const perp = canonicalPerp(A, B); const cx = (A.x + B.x) / 2 + perp.x * offset; const cy = (A.y + B.y) / 2 + perp.y * offset; return { x: 0.25 * A.x + 0.5 * cx + 0.25 * B.x, y: 0.25 * A.y + 0.5 * cy + 0.25 * B.y }; }
/* 自环:路径 + 中点 */ function selfLoopGeometry(node, idx, total) { const R = NODE_R; const count = Math.max(1, total); /* 多个自环均匀分布在节点周围 */ const baseAngle = -Math.PI / 2 + (idx * 2 * Math.PI) / count; const spread = 0.62; const a1 = baseAngle - spread; const a2 = baseAngle + spread; const sx = node.x + R * Math.cos(a1); const sy = node.y + R * Math.sin(a1); const ex = node.x + R * Math.cos(a2); const ey = node.y + R * Math.sin(a2);
/* 环的“顶点”位置(距离节点中心 2.4R) */ const loopDist = R * 2.4; const lx = node.x + Math.cos(baseAngle) * loopDist; const ly = node.y + Math.sin(baseAngle) * loopDist;
/* 二次贝塞尔控制点,使曲线经过 (lx, ly) */ const ctrlX = 2 * lx - 0.5 * (sx + ex); const ctrlY = 2 * ly - 0.5 * (sy + ey);
return {114 行未改动全部展开 <marker id="arrowNeg" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse"> <path d="M0,0 L10,5 L0,10 Z" fill="#dc2626"/> </marker> <marker id="arrowFlow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse"> <path d="M0,0 L10,5 L0,10 Z" fill="#60a5fa"/> </marker> </defs> <rect data-blank="1" x="0" y="0" width="${W}" height="${H}" fill="url(#grid)"/>`;
/* 边 */ const edgeDraws = []; for (const e of edges) { const A = nmap.get(e.a), B = nmap.get(e.b); if (!A || !B) continue;
const meta = edgeMeta.get(e.id) || { offset: 0, selfIdx: 0, selfTotal: 1 }; let d, mid; if (e.a === e.b) { const g = selfLoopGeometry(A, meta.selfIdx || 0, meta.selfTotal || 1);35 行未改动 html += `<path data-edge="${e.id}" d="${d}" fill="none" stroke="none" stroke-width="18" pointer-events="stroke" style="cursor:pointer"/>`; }
/* 容量标签 */ if (capEnabled) { for (const { e, mid } of edgeDraws) { const isNeg = isNegEdge(e); const txt = fmtNum((typeof e.cap === 'number') ? e.cap : 1); const bw = 12 + txt.length * 7.2; const bh = 18;
/* 自环的标签放在环顶略偏外 */ let lx = mid.x, ly = mid.y - 14; if (e.a !== e.b) { const meta = edgeMeta.get(e.id) || { offset: 0 }; if (Math.abs(meta.offset || 0) < 1) { /* 直线边:朝垂直于边的方向偏移(朝上) */ const A = nmap.get(e.a), B = nmap.get(e.b); const dx = B.x - A.x, dy = B.y - A.y; const dlen = Math.hypot(dx, dy) || 1; let px = -dy / dlen, py = dx / dlen;16 行未改动 </g>`; } }
/* 最大流箭头 + 流量数字 */ if (flowHighlight.size > 0) { for (const [edgeId, info] of flowHighlight) { const e = edges.find(x => x.id === edgeId); if (!e) continue; const A = nmap.get(e.a), B = nmap.get(e.b); if (!A || !B) continue; if (e.a === e.b) continue; // 自环不参与最大流可视化 if (e.a === e.b) continue;
const meta = edgeMeta.get(e.id) || { offset: 0 }; const mid = edgeMidpoint(A, B, meta.offset || 0);
42 行未改动 } } }
/* 连边预览 */ if (mode === 'edge' && pending !== null && hoverPt) { const pn = nmap.get(pending); if (pn) { html += `<line x1="${pn.x}" y1="${pn.y}" x2="${hoverPt.x}" y2="${hoverPt.y}" stroke="#2563eb" stroke-width="2" stroke-dasharray="6 6" opacity="0.55" pointer-events="none"/>`; } }
/* 顶点 */ for (let i = 0; i < nodes.length; i++) { const nd = nodes[i]; const isPend = pending === nd.id; const isHot = highlight.nodeIds.has(nd.id);127 行未改动全部展开 return maxV > PHYS.sleepSpeed; }
/* ============================================================ * 图分析(支持自环与重边) * 图分析 * ============================================================ */ function analyze() { const n = nodes.length, m = edges.length; const idx = new Map();9 行未改动 const a = idx.get(e.a), b = idx.get(e.b); if (a === undefined || b === undefined) continue;
if (a === b) { /* 自环:无向度数 +2;有向入度 +1、出度 +1 */ adjU[a].push(a); adjU[a].push(a); adjOut[a].push(a); adjIn[a].push(a);6 行未改动 } } const degU = adjU.map(a => a.length);
/* 连通分量(自环不影响连通性) */ const seen = new Array(n).fill(false); let comps = 0; for (let i = 0; i < n; i++) { if (seen[i]) continue;5 行未改动 } } const weakConnected = (n === 0) || comps === 1;
/* 无向意义下的环:注意自环本身也是环 - 若不考虑自环:m_self = 0 时 m > n - comps 表示有环 - 若存在自环,必然有环 */ let selfLoopCount = 0; for (const e of edges) if (e.a === e.b) selfLoopCount++; const effectiveM = m - selfLoopCount; // 去掉自环的边数(自环不增加连通性) const effectiveM = m - selfLoopCount; const cycleU = selfLoopCount > 0 || effectiveM > n - comps;
/* 有向环:Kahn 算法,自环会让节点永远入度 > 0 */ let cycleD = false; { const deg = indeg.slice(); const q = [];5 行未改动 } cycleD = cnt < n; }
/* 强连通 */ let stronglyConnected = true; if (n > 0) { const vis = new Array(n).fill(false); const order = [];16 行未改动 } stronglyConnected = c === 1; }
/* 是否为树:自环或重边都直接判定不是树 */ let isTree = false; if (n > 0) { if (!directed) { /* 无向树:连通、无自环、无重边、m == n-1 */ let hasMultiOrSelf = false; if (selfLoopCount > 0) hasMultiOrSelf = true; else { const pairSet = new Set();5 行未改动 } } isTree = weakConnected && m === n - 1 && !hasMultiOrSelf; } else { /* 有向树:弱连通、恰一个入度 0 的点、所有点入度 <= 1、无自环 */ const zeroIn = indeg.filter(d => d === 0).length; const allAtMost1 = indeg.every(d => d <= 1); isTree = weakConnected && zeroIn === 1 && allAtMost1 && selfLoopCount === 0; }69 行未改动 else if (nodes.length === 1) selDst.value = String(nodes[0].id); else selDst.value = ''; }
/* ============================================================ * 数据导出 * ============================================================ */ function generateExportText() { const idToNum = new Map(); nodes.forEach((nd, i) => idToNum.set(nd.id, i + 1));
const lines = []; lines.push(`${nodes.length} ${edges.length}`);
for (const e of edges) { const u = idToNum.get(e.a); const v = idToNum.get(e.b); if (u === undefined || v === undefined) continue;
if (capEnabled) { const w = (typeof e.cap === 'number' && Number.isFinite(e.cap)) ? e.cap : 1; lines.push(`${u} ${v} ${fullNumStr(w)}`); } else { lines.push(`${u} ${v}`); } } return lines.join('\n'); }
function updateExport() { exportArea.value = generateExportText(); }
function showExportStatus(msg, isErr) { exportStatus.className = 'code-status ' + (isErr ? 'err' : 'ok'); exportStatus.textContent = msg; clearTimeout(showExportStatus._timer); showExportStatus._timer = setTimeout(() => { exportStatus.textContent = ''; exportStatus.className = 'code-status'; }, 2200); }
async function copyExport() { const text = exportArea.value; if (!text) { showExportStatus('没有可复制的内容', true); return; } try { if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(text); showExportStatus('✓ 已复制到剪贴板', false); } else { throw new Error('no clipboard'); } } catch (err) { try { const wasReadonly = exportArea.readOnly; exportArea.readOnly = false; exportArea.select(); exportArea.setSelectionRange(0, text.length); const ok = document.execCommand('copy'); exportArea.readOnly = wasReadonly; window.getSelection().removeAllRanges(); if (ok) showExportStatus('✓ 已复制到剪贴板', false); else showExportStatus('复制失败,请手动选中复制', true); } catch (e2) { showExportStatus('复制失败,请手动选中复制', true); } } }
document.getElementById('btnExportCopy').addEventListener('click', copyExport);
exportCard.addEventListener('toggle', () => { if (exportCard.open) updateExport(); });
function updateUI() { numNodesEl.value = nodes.length; if (!chkTree.checked) numEdgesEl.value = edges.length;
const n = nodes.length; /* 上限按简单图算;实际允许重边/自环,所以这里只是随机生成的参考上限 */ const maxE = directed ? n * (n - 1) : n * (n - 1) / 2; numEdgesEl.max = Math.max(0, maxE);
let tagText = directed ? '有向图' : '无向图';2 行未改动 tagEl.innerHTML = tagText;
refreshSelectors(); renderAnalysis(); updateExport(); }
function refresh() { render();16 行未改动 nodes[i].y = cy + ry * Math.sin(ang); } }
/* 整理 */ function findTreeCentroid() { const adj = new Map(); for (const nd of nodes) adj.set(nd.id, []); for (const e of edges) {187 行未改动全部展开 const a = idx.get(e.a), b = idx.get(e.b); if (a === undefined || b === undefined) continue; adj[a].push(b); indeg[b]++; /* 自环:自己指向自己,入度已 +1,永远无法拓扑排序 */ }
let current = []; for (let i = 0; i < n; i++) if (indeg[i] === 0) current.push(i);6 行未改动 processed += current.length; const next = []; for (const u of current) { for (const v of adj[u]) { if (v === u) continue; // 自环不减少入度 if (v === u) continue; if (--indeg[v] === 0) next.push(v); } } next.sort((x, y) => x - y);71 行未改动 while (q.length) { const u = q.shift(); inQueue[u] = false; for (const [v, w] of adj[u]) { /* 跳过无意义的大正数松弛 */ if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; parent[v] = u; if (!inQueue[v]) {20 行未改动 } return { dist: dist[T], path }; }
/* 最大流:Edmonds-Karp。自环与负容量边忽略。 */ function maxFlow(sId, tId) { const n = nodes.length; const idx = new Map(); nodes.forEach((nd, i) => idx.set(nd.id, i));
const cap = Array.from({ length: n }, () => new Array(n).fill(0)); for (const e of edges) { const a = idx.get(e.a), b = idx.get(e.b); if (a === undefined || b === undefined) continue; if (a === b) continue; // 自环对最大流无贡献 if (a === b) continue; const c = edgeCap(e); if (c <= 0) continue; if (directed) cap[a][b] += c; else { cap[a][b] += c; cap[b][a] += c; }44 行未改动 }
const flowMap = new Map(); for (const e of edges) { if (e.a === e.b) continue; // 自环 if (e.a === e.b) continue; const a = idx.get(e.a), b = idx.get(e.b); if (a === undefined || b === undefined) continue; const netAB = origCap[a][b] - cap[a][b]; if (Math.abs(netAB) < 1e-9) continue;84 行未改动 for (let k = 0; k < r.path.length - 1; k++) { const u = nodes[r.path[k]].id; const v = nodes[r.path[k + 1]].id; if (u === v) continue; /* 有多条平行边时,选权重最小的那条高亮 */ let best = null, bestW = Infinity; for (const e of edges) { if (e.a === e.b) continue; if ((e.a === u && e.b === v) || (e.a === v && e.b === u)) {142 行未改动全部展开 refresh(); }
/* ============================================================ * 随机生成(不添加自环与重边,保持整洁) * 随机生成 * ============================================================ */ function randomGenerate() { const n = clamp(parseInt(numNodesEl.value, 10) || 0, 0, MAX_NODES); numNodesEl.value = n;61 行未改动 wake(); }
/* ============================================================ * 代码模式:解析(允许自环和重边) * 代码模式解析 * ============================================================ */ function parseCode(text) { const lines = text.split('\n') .map(l => l.trim())30 行未改动 } if (u < 1 || u > n || v < 1 || v > n) { throw new Error(`第 ${lineNum} 行顶点编号超出范围 [1, ${n}]`); } /* 自环:允许,但计入统计 */
let w = 1; if (parts.length >= 3) { w = parseFloat(parts[2]);133 行未改动全部展开 } else if (mode === 'edge') { if (pending === null) { pending = id; } else if (pending === id) { /* 同一节点再次点击 → 添加自环 */ edges.push({ id: edgeSeq++, a: id, b: id, cap: 1 }); pending = null; clearAllVisual(); } else { /* 不同节点 → 添加边(允许重边) */ edges.push({ id: edgeSeq++, a: pending, b: id, cap: 1 }); pending = null; clearAllVisual(); }99 行未改动 btn.classList.add('active'); directed = btn.dataset.type === 'directed';
if (!directed) { /* 切到无向图时,负权清零 */ let fixed = false; for (const e of edges) { if (typeof e.cap === 'number' && e.cap < 0) { e.cap = 0; fixed = true;118 行未改动全部展开 const r = stage.getBoundingClientRect(); W = Math.max(240, Math.round(r.width)); H = Math.max(240, Math.round(r.height)); } syncPhysSliders(); randomGenerate();})();</script></body>2 行未改动