版本比较
图-查看器
正文
增加 694 行删除 317 行
2 行未改动3456778910116 行未改动1819202122222324257 行未改动33343536383738394047 行未改动8889909194929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814910715015115215314 行未改动16816917017113017217317417517617717817918018118218318420 行未改动20520620720816720921021121221321421521621717721821922022118222222322422522610 行未改动23723823924020124124224324424534 行未改动2802812822832442842852862872882482492502512522532892902912922932942952962972552562982993003013023033043053063073083093103113123133143153163173183193203213223233243258 行未改动33433533633728233833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139234 行未改动4274284294303334314324334344356 行未改动44244344444534834935044644744844945045145225 行未改动4784794804814824834844854864873894884894904914926 行未改动4995005015024045035045055065075085094105105115125135144 行未改动5195205215225235245255265275285295305315325334274284295345355365375385395405415425435445455465475485495505515525535545555565578 行未改动56656756856945145245345445557057145857257357457557657757857958058158258358446758558646958758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870947471071147671271371471548048148248348471671771871948648748848949072072172272372472572672772850050172973073173250450550650750850951051151273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477552552677677777877978078178278378478578678778878922 行未改动81281381481555855981681781881982082182282382482530 行未改动8568578588598608618628638647 行未改动8728738748758768778788798808818826168838848858868878888898908918928938948958968978988996216229009019029039049059066286299079089099109116336349129139149159169179189193 行未改动92392492592664692792892964993065165265393193293393493593665565665765865966066166266366466566666766893793893994094194294394494594694794894995067167267395195295395495595667795795867995996096196296396468596596696796896997097197269369497397497597697797819 行未改动998999100010017221002100310041005100672872973010071008100910101011101210131014737101510161017101810191020102174410221023102410251026102710281029103075410311032103310341035103610371038763764765766767768769103910401041104210431044104570 行未改动1116111711181119848112011211122112311241125112611278578588591128112911301131113245 行未改动1178117911801181118211831184118511861187118811891190913914915119111921193119411951196119711987 行未改动1206120712081209931121012111212121312141215121612171218121932 行未改动1252125312541255125612571258125912601261126212631264126512669731267126812691270977127112721273127412751276127798412781279128012811282128322 行未改动13061307130813091310131113121313131413151316131713186 行未改动132513261327132810291030103113291330133113329 行未改动134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014217 行未改动14291430143114321433143414351436143714381439144014411072144214431444144514467 行未改动1454145514561457108810891090145814591460146114621463146414651098146614671468146910 行未改动14801481148214831117148414851486112114871488148914906 行未改动1497149814991500113611371138113911401141150115021503150411431505150615071508114815091510151115125 行未改动1518151915201521116215221523116515241525116811691170117111721173152615271528152915301531153215331181153415351536153715381187153915401190119115411192154215431195154415451198154615471548120215491550155115526 行未改动155915601561156215631564156515661220156715681569157012251571157215731574157515761577123312341235123615781579158015811240158215831243158415851586158715881589125012511590125215911592125515931594125815951596159715989 行未改动160816091610161112761612127816131614161516161617128412851286161816191620162116221623162416251291129212931626129416271628162912981630163116321633163416351636163716381308130913101639164016411642164313 行未改动165716581659166013321661166216631336166416651666166716681669167016711672167313461347134813491674167516761677135316781679168016811357168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617075 行未改动171317141715171613841717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217736 行未改动1780178117821783178417851786141614171418141914201421178717881789179017911792179317941795179614301797179817991800143218011802180318041805180618071439180818091810181118126 行未改动18191820182118221823182418251826182718281829183018311462183214641833183418351836183718381839147118401473147414751476147718411842184318441845184618478 行未改动185618571858185914941860186118621863186418651501186618671868186918701871187215091873151118741875151418761877187815181879188018811882188315241525188415261885152815291886188718881889189011 行未改动1902190319041905190619071908190919101911191219131914191519161917191819195 行未改动1925192619271928156215631564192919301931193219331934193519361937193819391940194119421943194419451572157315741946194719481949195019511952195319541955195619571577157815791958195919601961196217 行未改动19801981198219831605198419851986198719881611198919901991199219934 行未改动1998199920002001162420022003200420052006200716302008200920102011163420122013201420153 行未改动201920202021202216462023202420252026165120272028202920302031203220332034203516612036203720382039204016671668204120422043204420452046204720482049205020512052205316742054205520562057205825 行未改动20842085208620871708208820892090209111 行未改动210321042105210617282107210821092110211121122113211417372115211621172118211921202121212221231747174817492124212521261752212721282129213015 行未改动21462147214821491776215021512152215321547 行未改动216221632164216517921793216621672168216921702171217221732174180121752176217721786 行未改动218521862187218818161817181821892190219118221823182421922193219421951826219621972198219922002201220222032204220522062207220822091830183118321833183418352210221122122213183922142215221622172218221922201846222122221849222322242225222622271855222822292230223118602232223322342235223618662237223822391870224022412242224322442245224622471879188018811882224822492250225122522253225422552256225722582259226022611891189218931894189518961897189818991900190119021903190419051906190719081909226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622876 行未改动22942295229622971924229822992300230124 行未改动232623272328232923302331233223331959196023341961196223352336233723382339234023 行未改动23642365236623671995199623682369237023712372237320022003200420052374237523762377200820092378237923802381238210 行未改动23932394239523962028239723982399240014 行未改动241524162417241820512419242024212055242224232058242424252426206224272428242924304 行未改动2435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582082245924602461246224637 行未改动247124722473247420982099210024752476247724782479248082 行未改动2563256425652566256725682569257025712 行未改动2 行未改动<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>图论可视化 · 2D + 图算法 + 代码模式</title><title>图论可视化</title><style> :root{ --bg:#f1f5f9; --border:#e2e8f0; --text:#0f172a; --muted:#64748b; --primary:#2563eb;6 行未改动 -webkit-font-smoothing:antialiased; } .app{display:flex;height:100vh;}
/* ================= 侧栏 ================= */ .panel{ width:350px;flex:0 0 350px;background:#fff;border-right:1px solid var(--border); padding:18px 16px 40px;overflow-y:auto;display:flex;flex-direction:column;gap:12px; }7 行未改动 font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:var(--muted); margin:0 0 10px;font-weight:700; }
/* details 折叠卡片 */ details.card summary{ cursor:pointer;font-size:13px;font-weight:700;color:var(--text); list-style:none;display:flex;align-items:center;gap:7px; margin:-12px;padding:12px;border-radius:12px;user-select:none;47 行未改动 .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;}
/* ================= 分析 ================= */ .stats{display:flex;gap:8px;margin-bottom:10px;} .stat{flex:1;background:#fff;border:1px solid var(--border);border-radius:9px;padding:8px;text-align:center;} .stat span{display:block;font-size:11px;color:var(--muted);margin-bottom:2px;} .stat b{font-size:18px;}14 行未改动 padding:3px 7px;color:#475569;font-family:ui-monospace,SFMono-Regular,Menlo,monospace; } .empty{font-size:12.5px;color:var(--muted);margin:0;line-height:1.7;}
/* ================= 算法结果 ================= */ .algo-result{ margin-top:10px;font-size:12.5px;color:#334155;background:#fff; border:1px solid var(--border);border-radius:9px;padding:10px 11px; line-height:1.75;word-break:break-word;min-height:44px; } .algo-result .k{color:#2563eb;font-weight:700;font-family:ui-monospace,Menlo,monospace;} .algo-result .err{color:#b91c1c;font-weight:600;} .algo-result .inf{color:#b45309;font-weight:700;font-family:ui-monospace,Menlo,monospace;} .algo-result .neg{color:#dc2626;font-weight:700;font-family:ui-monospace,Menlo,monospace;} .algo-result .seq{ display:inline-block;font-family:ui-monospace,Menlo,monospace; background:#eff6ff;color:#1d4ed8;border-radius:5px;padding:1px 5px;margin:1px 0; }20 行未改动 padding:2px 8px;border-radius:6px;border:1px solid transparent;font-weight:700; } .topo-note{font-size:11px;color:var(--muted);margin-top:9px;line-height:1.5;}
/* ================= 画布 ================= */ .stage{flex:1;position:relative;min-width:0;background:#fbfdff;} svg{display:block;width:100%;height:100%;touch-action:none;} .tag{ position:absolute;left:14px;bottom:12px;font-size:12px;color:#94a3b8; background:rgba(255,255,255,.85);padding:5px 10px;border-radius:8px; border:1px solid var(--border);pointer-events:none; } .tag b{color:#f59e0b;}
/* ================= 边设置弹窗 ================= */ .edge-popup{ position:absolute;display:none;z-index:100; background:#fff;border:1px solid #cbd5e1;border-radius:10px; box-shadow:0 10px 28px rgba(15,23,42,.18); padding:12px;min-width:210px;font-size:13px; padding:12px;min-width:230px;font-size:13px; } .edge-popup .popup-header{ font-size:11px;text-transform:uppercase;letter-spacing:.08em; color:#64748b;font-weight:700;margin-bottom:8px;10 行未改动 font-size:12.5px;color:#334155;flex:0 0 auto; } .edge-popup input[type=number]{ flex:1;min-width:0;padding:6px 9px;border:1px solid #cbd5e1;border-radius:7px; font-size:13px;font-family:inherit;outline:none;text-align:right; font-size:13px;font-family:ui-monospace,Menlo,monospace;outline:none;text-align:right; color:var(--text);background:#fff;transition:.15s; } .edge-popup input[type=number]:focus{ border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,.12);34 行未改动 <div style="font-size:12px;color:#64748b;line-height:1.7;background:#eef2f7;border-radius:8px;padding:8px 10px;margin-bottom:2px;"> <b style="color:#334155">格式</b>(顶点编号 1..n):<br> 第一行:<code style="background:#fff;padding:1px 5px;border-radius:4px;color:#1d4ed8;">n m</code><br> 随后 m 行,每行:<code style="background:#fff;padding:1px 5px;border-radius:4px;color:#1d4ed8;">u v</code> 或 <code style="background:#fff;padding:1px 5px;border-radius:4px;color:#1d4ed8;">u v w</code><br> 若存在 w 则自动启用容量 / 边权。<br> <b style="color:#334155">w 支持任意实数</b>;<b style="color:#dc2626">有向图支持负权</b>。<br> <b style="color:#334155">支持自环与重边</b>(u=v 或同一对顶点多次出现)。<br> <span style="color:#94a3b8">支持 # 开头的注释行。</span> </div> <textarea id="codeInput" class="code-area" spellcheck="false"placeholder="6 81 2 41 3 32 3 12 4 23 5 6placeholder="6 91 1 21 2 2.51 2 3.71 3 3.142 3 0.52 4 1.23 5 4.84 5 34 6 25 6 4"></textarea>5 6 1.5"></textarea> <div class="btn-row" style="margin-top:8px"> <button class="btn" id="btnCodeSample">📄 示例</button> <button class="btn" id="btnCodeClear">清空输入</button> </div> <button class="btn primary" id="btnCodeApply" style="margin-top:8px">▶ 应用代码 (Ctrl+Enter)</button> <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">8 行未改动
<section class="card"> <h2>容量 / 边权</h2> <label class="check"><input type="checkbox" id="chkCap"> 启用容量 / 边权(默认 1)</label> <p class="hint">开启后,图中边会显示容量数值;<b>右键点击任意边</b>可修改其容量或删除它。</p> <p class="hint">支持任意实数。<b>有向图可输入负权</b>(最短路会切换为 SPFA,能检测负环)。无向图负权会形成负环,因此禁止。</p> </section>
<section class="card"> <h2>物理引擎</h2> <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>34 行未改动 <div class="edge-popup" id="edgePopup"> <div class="popup-header" id="popupHeader">边设置</div> <div class="popup-row"> <label>容量 / 边权</label> <input type="number" id="popupCapInput" min="0" max="9999" step="1" value="1"> <input type="number" id="popupCapInput" step="any" value="1"> </div> <div class="popup-actions"> <button class="save" id="popupSave">保存</button> <button class="delete" id="popupDelete">删除</button>6 行未改动<script>(() => { 'use strict';
/* ============================================================ * 常量与状态 * ============================================================ */ const NODE_R = 20; const MAX_NODES = 60; const MAX_WEIGHT = 1e9;
const LAYER_PALETTE = [ { fill:'#dbeafe', stroke:'#2563eb', text:'#1e40af' }, { fill:'#d1fae5', stroke:'#059669', text:'#065f46' },25 行未改动 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 = []; // {id, x, y, vx, vy} let nodes = []; let edges = []; // {id, a, b, cap} let nodeSeq = 1; let edgeSeq = 1;
6 行未改动
let capEnabled = false; let popupEdgeId = null;
/* 三种可视化高亮(互斥) */ let highlight = { nodeIds: new Set(), edgeIds: new Set() }; let topoColorMap = new Map(); let flowHighlight = new Map();
let edgeMeta = new Map();
/* ============================================================ * 物理参数 * 物理参数(可通过滑块调整) * ============================================================ */ const PHYS = { restitution: 0.78, damping: 0.925,4 行未改动 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;
/* ============================================================ * 小工具 * ============================================================ */ const clamp = (v, a, b) => Math.max(a, Math.min(b, v)); const getNode = id => nodes.find(n => n.id === id); const idxOf = id => nodes.findIndex(n => n.id === id); const nameOf = id => { const i = idxOf(id); return i >= 0 ? `v${i + 1}` : '?'; };
function fmtNum(v) { if (typeof v !== 'number' || !Number.isFinite(v)) return '?'; if (Number.isInteger(v)) return String(v); const abs = Math.abs(v); if (abs !== 0 && (abs < 1e-3 || abs >= 1e6)) return v.toExponential(2); 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 hasEdge(a, b) { if (directed) return edges.some(e => e.a === a && e.b === b); return edges.some(e => (e.a === a && e.b === b) || (e.a === b && e.b === a)); }
function edgeCap(e) { if (!capEnabled) return 1; return (typeof e.cap === 'number' && e.cap >= 0) ? e.cap : 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; }
function clearHighlight() { highlight = { nodeIds: new Set(), edgeIds: new Set() }; } function clearTopo() { topoColorMap = new Map(); } function clearFlow() { flowHighlight = new Map(); } function clearAllVisual() { clearHighlight(); clearTopo(); clearFlow(); closePopup(); }
/* ============================================================ * 几何 * 物理调参滑块 * ============================================================ */ function edgePath(A, B, curved, arrowRoom) { 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); if (!groups.has(key)) groups.set(key, []); groups.get(key).push(e); }
for (const [key, group] of groups) { if (group.length === 1) { 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; const hasB = backward.length > 0;
if (hasF && hasB) { forward.forEach((e, i) => edgeMeta.set(e.id, { offset: 28 + i * 30 })); backward.forEach((e, i) => edgeMeta.set(e.id, { offset: -28 - i * 30 })); } else { const list = hasF ? forward : backward; const total = list.length; list.forEach((e, i) => { edgeMeta.set(e.id, { offset: (i - (total - 1) / 2) * 30 }); }); } } }
const selfGroups = new Map(); for (const e of edges) { if (e.a !== e.b) continue; if (!selfGroups.has(e.a)) selfGroups.set(e.a, []); selfGroups.get(e.a).push(e); } for (const [nodeId, list] of selfGroups) { list.forEach((e, i) => { edgeMeta.set(e.id, { selfIdx: i, selfTotal: list.length, offset: 0 }); }); } }
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; const r1 = NODE_R; const r2 = NODE_R + (arrowRoom ? 3 : 0); const r2 = NODE_R + (directed ? 3 : 0);
if (!curved) { 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 lo = A.id < B.id ? A : B; const hi = A.id < B.id ? B : A; const cdx = hi.x - lo.x, cdy = hi.y - lo.y; const cd = Math.hypot(cdx, cdy) || 1; const cpx = -cdy / cd, cpy = cdx / cd; 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 sign = (A.id < B.id) ? 1 : -1; const off = 28 * sign; const cx = (A.x + B.x) / 2 + cpx * off; const cy = (A.y + B.y) / 2 + cpy * off;
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;
const edx = cx - B.x, edy = cy - B.y, ed = Math.hypot(edx, edy) || 1; const ex = B.x + edx / ed * r2, ey = B.y + edy / ed * r2;
return `M ${sx} ${sy} Q ${cx} ${cy} ${ex} ${ey}`; }
function edgeMidpoint(A, B, curved) { if (!curved) { function edgeMidpoint(A, B, offset) { if (Math.abs(offset) < 1) { return { x: (A.x + B.x) / 2, y: (A.y + B.y) / 2 }; } const lo = A.id < B.id ? A : B; const hi = A.id < B.id ? B : A; const cdx = hi.x - lo.x, cdy = hi.y - lo.y; const cd = Math.hypot(cdx, cdy) || 1; const cpx = -cdy / cd, cpy = cdx / cd; const sign = (A.id < B.id) ? 1 : -1; const off = 28 * sign; const cx = (A.x + B.x) / 2 + cpx * off; const cy = (A.y + B.y) / 2 + cpy * off; 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);
const loopDist = R * 2.4; const lx = node.x + Math.cos(baseAngle) * loopDist; const ly = node.y + Math.sin(baseAngle) * loopDist;
const ctrlX = 2 * lx - 0.5 * (sx + ex); const ctrlY = 2 * ly - 0.5 * (sy + ey);
return { path: `M ${sx} ${sy} Q ${ctrlX} ${ctrlY} ${ex} ${ey}`, midX: lx, midY: ly, endX: ex, endY: ey }; }
/* ============================================================ * 弹窗 * ============================================================ */ function openPopup(edge, clientX, clientY) { popupEdgeId = edge.id; const ia = idxOf(edge.a), ib = idxOf(edge.b); popupHeader.textContent = `边 v${ia + 1} ${directed ? '→' : '—'} v${ib + 1}`; popupCapInput.value = edge.cap ?? 1; if (edge.a === edge.b) { popupHeader.textContent = `自环 v${ia + 1} ↺`; } else { popupHeader.textContent = `边 v${ia + 1} ${directed ? '→' : '—'} v${ib + 1}`; } popupCapInput.value = fmtNum(edge.cap ?? 1);
if (directed) popupCapInput.removeAttribute('min'); else popupCapInput.setAttribute('min', '0');
edgePopup.style.display = 'block';
const stageRect = stage.getBoundingClientRect(); let x = clientX - stageRect.left + 12;22 行未改动 function savePopup() { if (popupEdgeId === null) return; const edge = edges.find(x => x.id === popupEdgeId); if (!edge) { closePopup(); return; } const v = parseInt(popupCapInput.value, 10); edge.cap = (isNaN(v) || v < 0) ? 1 : Math.min(v, 9999); let v = parseFloat(popupCapInput.value); if (!Number.isFinite(v)) v = 1; if (!directed && v < 0) v = 0; v = Math.min(v, MAX_WEIGHT); v = Math.max(v, -MAX_WEIGHT); edge.cap = v; closePopup(); clearAllVisual(); refresh(); }30 行未改动 requestAnimationFrame(() => { rafPending = false; render(); }); }
function render() { computeEdgeMeta(); const nmap = new Map(nodes.map(n => [n.id, n]));
let html = ` <defs>7 行未改动 <marker id="arrowHot" 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="#f59e0b"/> </marker> <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> </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); d = g.path; mid = { x: g.midX, y: g.midY }; } else { d = edgePath(A, B, meta.offset || 0); mid = edgeMidpoint(A, B, meta.offset || 0); } edgeDraws.push({ e, d, mid }); }
const curved = directed && edges.some(o => o.a === e.b && o.b === e.a); const d = edgePath(A, B, curved, directed); for (const { e, d } of edgeDraws) { const hot = highlight.edgeIds.has(e.id); const hasFlow = flowHighlight.has(e.id); const isNeg = isNegEdge(e);
let sw = 2; if (capEnabled) { const c = (typeof e.cap === 'number') ? e.cap : 1; sw = Math.min(6, 2 + 0.35 * Math.max(0, c - 1)); const c = (typeof e.cap === 'number' && Number.isFinite(e.cap)) ? e.cap : 1; sw = Math.min(6, 2 + 0.35 * Math.max(0, Math.abs(c) - 1)); } if (hot) sw = Math.max(sw, 3.2);
const stroke = hot ? '#f59e0b' : '#94a3b8'; const marker = hot && directed ? 'url(#arrowHot)' : (directed ? 'url(#arrow)' : ''); let stroke = '#94a3b8'; let marker = directed ? 'url(#arrow)' : ''; if (hot) { stroke = '#f59e0b'; marker = directed ? 'url(#arrowHot)' : ''; } else if (isNeg) { stroke = '#dc2626'; marker = directed ? 'url(#arrowNeg)' : ''; }
html += `<path d="${d}" fill="none" stroke="${stroke}" stroke-width="${sw}" stroke-linecap="round" pointer-events="none" ${marker ? `marker-end="${marker}"` : ''}/>`;3 行未改动 stroke-width="${sw + 4}" stroke-linecap="round" pointer-events="none"/>`; }
html += `<path data-edge="${e.id}" d="${d}" fill="none" stroke="none" stroke-width="16" pointer-events="stroke" style="cursor:pointer"/>`; stroke-width="18" pointer-events="stroke" style="cursor:pointer"/>`; }
/* 容量标签 */ if (capEnabled) { for (const e of edges) { const A = nmap.get(e.a), B = nmap.get(e.b); if (!A || !B) continue; 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;
const len = Math.hypot(B.x - A.x, B.y - A.y); if (len < 76) continue;
const curved = directed && edges.some(o => o.a === e.b && o.b === e.a); const mid = edgeMidpoint(A, B, curved);
let lx = mid.x, ly = mid.y; if (!curved) { const dx = B.x - A.x, dy = B.y - A.y; const d = Math.hypot(dx, dy) || 1; let px = -dy / d, py = dx / d; if (py > 0) { px = -px; py = -py; } lx += px * 15; ly += py * 15; 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; if (py > 0) { px = -px; py = -py; } lx = mid.x + px * 15; ly = mid.y + py * 15; } }
const txt = String((typeof e.cap === 'number') ? e.cap : 1); const bw = 10 + txt.length * 7.5; const bh = 18; const bgFill = isNeg ? '#fef2f2' : '#ffffff'; const bgStroke = isNeg ? '#fecaca' : '#bfdbfe'; const txtFill = isNeg ? '#dc2626' : '#1d4ed8';
html += `<g pointer-events="none"> <rect x="${lx - bw / 2}" y="${ly - bh / 2}" width="${bw}" height="${bh}" rx="5" fill="#ffffff" stroke="#bfdbfe" stroke-width="1"/> fill="${bgFill}" stroke="${bgStroke}" stroke-width="1"/> <text x="${lx}" y="${ly}" text-anchor="middle" dominant-baseline="central" font-size="11.5" font-weight="700" fill="#1d4ed8" font-size="11" font-weight="700" fill="${txtFill}" font-family="ui-monospace,Menlo,monospace">${txt}</text> </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;
const curved = directed && edges.some(o => o.a === e.b && o.b === e.a); const mid = edgeMidpoint(A, B, curved); const meta = edgeMeta.get(e.id) || { offset: 0 }; const mid = edgeMidpoint(A, B, meta.offset || 0);
let dx, dy; if (info.dir === 'a→b') { dx = B.x - A.x; dy = B.y - A.y; } else { dx = A.x - B.x; dy = A.y - B.y; }19 行未改动 if (info.amount > 1) { const numOffset = tipLen * 0.5 + 13; let numX = mid.x + ux * numOffset; let numY = mid.y + uy * numOffset;
const distToTarget = Math.hypot(B.x - numX, B.y - numY); if (distToTarget < NODE_R + 14) { numX = mid.x - ux * numOffset; numY = mid.y - uy * numOffset; }
const txt = String(info.amount); const bw = 10 + txt.length * 7; const txt = fmtNum(info.amount); const bw = 12 + txt.length * 6.8; const bh = 16;
html += `<g pointer-events="none"> <rect x="${numX - bw / 2}" y="${numY - bh / 2}" width="${bw}" height="${bh}" rx="5" fill="rgba(255,255,255,0.94)" stroke="rgba(37,99,235,0.55)" stroke-width="1"/> <text x="${numX}" y="${numY}" text-anchor="middle" dominant-baseline="central" font-size="11" font-weight="700" fill="#1d4ed8" font-size="10.5" font-weight="700" fill="#1d4ed8" font-family="ui-monospace,Menlo,monospace">${txt}</text> </g>`; } } }
/* 连边预览 */ 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); const lc = topoColorMap.get(nd.id);
let fill = '#ffffff', stroke = '#64748b', sw = 2, txt = '#0f172a';
if (isPend) { fill = '#dbeafe'; stroke = '#2563eb'; sw = 2.5; } else if (isHot) { fill = '#fef3c7'; stroke = '#f59e0b'; sw = 2.8; } else if (lc) { fill = lc.fill; stroke = lc.stroke; sw = 2.6; txt = lc.text; } if (isPend) { fill = '#dbeafe'; stroke = '#2563eb'; sw = 2.5; } else if (isHot) { fill = '#fef3c7'; stroke = '#f59e0b'; sw = 2.8; } else if (lc) { fill = lc.fill; stroke = lc.stroke; sw = 2.6; txt = lc.text; }
const cursor = mode === 'erase' ? 'pointer' : mode === 'edge' ? 'crosshair' : 'grab';70 行未改动 for (let i = 0; i < nodes.length; i++) { const a = nodes[i]; for (let j = i + 1; j < nodes.length; j++) { const b = nodes[j];
let dx = b.x - a.x; let dy = b.y - a.y; let d = Math.hypot(dx, dy); if (d >= minD) continue;
if (d < 0.001) { const ang = Math.random() * Math.PI * 2; dx = Math.cos(ang); dy = Math.sin(ang); d = 0.001; } else { dx /= d; dy /= d; } } else { dx /= d; dy /= d; }
const overlap = minD - d; const aFix = (a === dragged) ? 0 : 1; const bFix = (b === dragged) ? 0 : 1;45 行未改动
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) { adjU[a].push(a); adjU[a].push(a); adjOut[a].push(a); adjIn[a].push(a); outdeg[a]++; indeg[a]++; } else { adjU[a].push(b); adjU[b].push(a); adjOut[a].push(b); adjIn[b].push(a); outdeg[a]++; indeg[b]++; adjU[a].push(b); adjU[b].push(a); adjOut[a].push(b); adjIn[b].push(a); outdeg[a]++; indeg[b]++; } } const degU = adjU.map(a => a.length);
const seen = new Array(n).fill(false);7 行未改动 for (const v of adjU[u]) if (!seen[v]) { seen[v] = true; stack.push(v); } } } const weakConnected = (n === 0) || comps === 1; const cycleU = m > n - comps;
let selfLoopCount = 0; for (const e of edges) if (e.a === e.b) selfLoopCount++; const effectiveM = m - selfLoopCount; const cycleU = selfLoopCount > 0 || effectiveM > n - comps;
let cycleD = false; { const deg = indeg.slice(); const q = [];32 行未改动
let isTree = false; if (n > 0) { if (!directed) { let hasMultiOrSelf = false; if (selfLoopCount > 0) hasMultiOrSelf = true; else { const pairSet = new Set(); for (const e of edges) { if (e.a === e.b) { hasMultiOrSelf = true; break; } const k = e.a < e.b ? `${e.a}-${e.b}` : `${e.b}-${e.a}`; if (pairSet.has(k)) { hasMultiOrSelf = true; break; } pairSet.add(k); } } isTree = weakConnected && m === n - 1; isTree = weakConnected && m === n - 1 && !hasMultiOrSelf; } else { const zeroIn = indeg.filter(d => d === 0).length; const allAtMost1 = indeg.every(d => d <= 1); isTree = weakConnected && zeroIn === 1 && allAtMost1; isTree = weakConnected && zeroIn === 1 && allAtMost1 && selfLoopCount === 0; } }
return { n, m, comps, weakConnected, stronglyConnected, hasCycle: directed ? cycleD : cycleU, isTree, indeg, outdeg, degU isTree, indeg, outdeg, degU, selfLoopCount }; }
function renderAnalysis() {22 行未改动 html += `<li><span class="lbl">强连通</span><span class="rgt">${badge(r.stronglyConnected, '是', '否')}</span></li>`; html += `<li><span class="lbl">是否含环</span><span class="rgt">${badge(r.hasCycle, '有环', '无环')}</span></li>`; html += `<li><span class="lbl">是否为有向树</span><span class="rgt">${badge(r.isTree, '是 ✔', '否 ✘')}</span></li>`; }
if (r.selfLoopCount > 0) { html += `<li><span class="lbl">自环数量</span> <span class="rgt"><span class="badge no">${r.selfLoopCount}</span></span></li>`; } html += `</ul>`;
html += `<p class="deg-title">${directed ? '各顶点入度 / 出度' : '各顶点度数'}</p><div class="deg-list">`; nodes.forEach((nd, i) => {6 行未改动 html += `</div>`; analysisEl.innerHTML = html; }
/* ============================================================ * UI 同步 * ============================================================ */ function refreshSelectors() { const oldSrc = selSrc.value; const oldDst = selDst.value; const opts = nodes.map((nd, i) => `<option value="${nd.id}">v${i + 1}</option>`).join('');9 行未改动 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;
7 行未改动 tagEl.innerHTML = tagText;
refreshSelectors(); renderAnalysis(); updateExport(); }
function refresh() { render(); updateUI(); }
/* ============================================================ * 布局:圆形 * 布局 * ============================================================ */ function layoutCircle() { const n = nodes.length; if (n === 0) return;7 行未改动 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) { if (e.a === e.b) continue; adj.get(e.a).push(e.b); adj.get(e.b).push(e.a); }
function bfs(start) { const dist = new Map([[start, 0]]); const parent = new Map([[start, null]]); const queue = [start];10 行未改动 } } return { last, parent }; }
const start = nodes[0].id; const r1 = bfs(start); const r2 = bfs(r1.last);
let cur = r2.last; const path = [cur]; while (cur !== r1.last) { cur = r2.parent.get(cur);6 行未改动 function computeTreeLayout(rootId) { const adj = new Map(); for (const nd of nodes) adj.set(nd.id, []); for (const e of edges) { if (directed) { adj.get(e.a).push(e.b); } else { adj.get(e.a).push(e.b); adj.get(e.b).push(e.a); } if (e.a === e.b) continue; if (directed) adj.get(e.a).push(e.b); else { adj.get(e.a).push(e.b); adj.get(e.b).push(e.a); } }
const children = new Map(); const visited = new Set([rootId]); const depth = new Map([[rootId, 0]]); const queue = [rootId];
while (queue.length) { const u = queue.shift(); const kids = []; for (const v of adj.get(u) || []) {5 行未改动 } } children.set(u, kids); }
const xs = new Map(); let cursor = 0;
function place(id) { const kids = children.get(id) || []; if (kids.length === 0) { const x = cursor; cursor += 1; xs.set(id, x); return x; } if (kids.length === 0) { const x = cursor; cursor += 1; xs.set(id, x); return x; } let sum = 0; for (const c of kids) sum += place(c); const x = sum / kids.length; xs.set(id, x); return x; } place(rootId);
return { xs, depth, numLeaves: cursor }; }
function applyTreeLayout(rootId) { const { xs, depth, numLeaves } = computeTreeLayout(rootId);
let maxDepth = 0; for (const d of depth.values()) maxDepth = Math.max(maxDepth, d);
const paddingX = 60; const paddingX = 60, paddingY = 70; const paddingY = 70; const availW = Math.max(1, W - paddingX * 2); const availH = Math.max(1, H - paddingY * 2 - NODE_R);
const spacingX = numLeaves <= 1 ? 0 : Math.min(160, availW / (numLeaves - 1)); const spacingY = maxDepth <= 0 ? 0 : Math.min(130, availH / maxDepth);
const totalW = (numLeaves - 1) * spacingX; const offsetX = (W - totalW) / 2; const offsetY = paddingY;
for (const nd of nodes) { const x = xs.get(nd.id); const d = depth.get(nd.id); if (x === undefined || d === undefined) continue;6 行未改动 function applyLayeredLayout() { const adj = new Map(); for (const nd of nodes) adj.set(nd.id, []); for (const e of edges) { if (e.a === e.b) continue; adj.get(e.a).push(e.b); adj.get(e.b).push(e.a); }
const level = new Map(); const sorted = [...nodes].sort((a, b) => (adj.get(b.id) || []).length - (adj.get(a.id) || []).length );
for (const startNode of sorted) { if (level.has(startNode.id)) continue; level.set(startNode.id, 0); const queue = [startNode.id]; while (queue.length) { const u = queue.shift(); for (const v of adj.get(u) || []) { if (!level.has(v)) { level.set(v, level.get(u) + 1); queue.push(v); } if (!level.has(v)) { level.set(v, level.get(u) + 1); queue.push(v); } } } }
let maxLevel = 0; for (const l of level.values()) maxLevel = Math.max(maxLevel, l);
const byLevel = new Map(); for (const nd of nodes) { const l = level.get(nd.id) || 0; if (!byLevel.has(l)) byLevel.set(l, []); byLevel.get(l).push(nd.id); }
const paddingX = 60; const paddingX = 60, paddingY = 70; const paddingY = 70; const availW = Math.max(1, W - paddingX * 2); const availH = Math.max(1, H - paddingY * 2 - NODE_R);
const numLevels = maxLevel + 1; const spacingY = numLevels <= 1 ? 0 : Math.min(130, availH / (numLevels - 1));
for (const [l, ids] of byLevel) { const spacingX = ids.length <= 1 ? 0 : Math.min(160, availW / (ids.length - 1)); const totalW = (ids.length - 1) * spacingX; const startX = (W - totalW) / 2;9 行未改动 }
function tidyLayout() { if (nodes.length === 0) return;
const r = analyze();
if (r.isTree) { let rootId; if (directed) { const indeg = new Map(); nodes.forEach(nd => indeg.set(nd.id, 0)); for (const e of edges) indeg.set(e.b, indeg.get(e.b) + 1); for (const [id, d] of indeg) { if (d === 0) { rootId = id; break; } for (const e of edges) { if (e.a === e.b) continue; indeg.set(e.b, indeg.get(e.b) + 1); } for (const [id, d] of indeg) if (d === 0) { rootId = id; break; } } else { rootId = findTreeCentroid(); }
if (rootId !== undefined) { applyTreeLayout(rootId); if (rootId !== undefined) applyTreeLayout(rootId); } } else { applyLayeredLayout(); }
nodes.forEach(nd => { nd.vx = 0; nd.vy = 0; }); refresh(); }
/* ============================================================ * 图算法核心 * ============================================================ */
function topoSort() { if (!directed) { return { ok: false, msg: '拓扑排序仅适用于有向图。请先切换到「有向图」。' }; } if (!directed) return { ok: false, msg: '拓扑排序仅适用于有向图。' }; const n = nodes.length; if (n === 0) return { ok: false, msg: '画布为空,请先添加顶点。' };
const idx = new Map();13 行未改动 current.sort((x, y) => x - y);
const levels = []; let processed = 0;
while (current.length) { levels.push(current); processed += current.length;
const next = []; for (const u of current) { for (const v of adj[u]) { if (v === u) continue; if (--indeg[v] === 0) next.push(v); } } next.sort((x, y) => x - y); current = next; }
if (processed < n) { return { ok: false, msg: '图中存在环,不存在拓扑排序。' }; } if (processed < n) return { ok: false, msg: '图中存在环(或有自环),不存在拓扑排序。' }; return { ok: true, levels }; }
function shortestPath(sId, tId) { function buildAdj() { const n = nodes.length; const idx = new Map(); nodes.forEach((nd, i) => idx.set(nd.id, i));
const adj = Array.from({ length: n }, () => []); for (const e of edges) { const a = idx.get(e.a), b = idx.get(e.b); if (a === undefined || b === undefined) continue; const w = edgeCap(e); adj[a].push([b, w]); if (!directed) adj[b].push([a, w]); } return { n, idx, adj }; }
function shortestPath(sId, tId) { const { n, idx, adj } = buildAdj(); const S = idx.get(sId), T = idx.get(tId); if (S === undefined || T === undefined) return null; if (S === T) return { dist: 0, path: [S] };
if (directed) return spfa(adj, S, T, n); return dijkstra(adj, S, T, n); }
function dijkstra(adj, S, T, n) { const dist = new Array(n).fill(Infinity); const parent = new Array(n).fill(-1); const visited = new Array(n).fill(false); dist[S] = 0;5 行未改动 } if (u === -1) break; visited[u] = true; if (u === T) break;
for (const [v, w] of adj[u]) { if (!visited[v] && dist[u] + w < dist[v]) { dist[v] = dist[u] + w; parent[v] = u; } } } if (dist[T] === Infinity) return { dist: Infinity, path: null };
const path = []; let v = T; while (v !== -1) { path.unshift(v); if (v === S) break; v = parent[v]; } return { dist: dist[T], path }; }
function spfa(adj, S, T, n) { const dist = new Array(n).fill(Infinity); const parent = new Array(n).fill(-1); const inQueue = new Array(n).fill(false); const enqueueCnt = new Array(n).fill(0);
dist[S] = 0; const q = [S]; inQueue[S] = true; enqueueCnt[S] = 1;
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]) { q.push(v); inQueue[v] = true; enqueueCnt[v]++; if (enqueueCnt[v] > n) return { negativeCycle: true }; } } } }
if (dist[T] === Infinity) return { dist: Infinity, path: null };
const path = []; let v = T; const guard = new Set(); while (v !== -1) { path.unshift(v); if (v === S) break; if (guard.has(v)) break; guard.add(v); v = parent[v]; } return { dist: dist[T], path }; }6 行未改动 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; const c = edgeCap(e); if (c <= 0) continue; if (directed) { cap[a][b] += c; } else { cap[a][b] += c; cap[b][a] += c; } if (directed) cap[a][b] += c; else { cap[a][b] += c; cap[b][a] += c; } } const origCap = cap.map(r => r.slice());
const S = idx.get(sId), T = idx.get(tId); if (S === undefined || T === undefined) return null; if (S === T) return { value: 0, flowMap: new Map() };
let flow = 0; const INF = 1e9; const INF = 1e18; const EPS = 1e-9; let safety = 0;
while (true) { while (safety++ < 5000) { const parent = new Array(n).fill(-1); parent[S] = S; const q = [S]; while (q.length && parent[T] === -1) { const u = q.shift(); for (let v = 0; v < n; v++) { if (parent[v] === -1 && cap[u][v] > 0) { if (parent[v] === -1 && cap[u][v] > EPS) { parent[v] = u; q.push(v); } }6 行未改动 const u = parent[v]; bottleneck = Math.min(bottleneck, cap[u][v]); v = u; } if (bottleneck <= EPS) break;
v = T; while (v !== S) { const u = parent[v]; cap[u][v] -= bottleneck; cap[v][u] += bottleneck; v = u; }
flow += bottleneck; if (bottleneck === 0) break; }
const flowMap = new Map(); for (const e of edges) { 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 (netAB > 0) { flowMap.set(e.id, { dir: 'a→b', amount: netAB }); } else if (netAB < 0) { flowMap.set(e.id, { dir: 'b→a', amount: -netAB }); } if (Math.abs(netAB) < 1e-9) continue; if (netAB > 0) flowMap.set(e.id, { dir: 'a→b', amount: netAB }); else flowMap.set(e.id, { dir: 'b→a', amount: -netAB }); }
return { value: flow, flowMap }; }8 行未改动 }
function showTopo() { const r = topoSort();
if (!r.ok) { algoResult.innerHTML = `<span class="err">${r.msg}</span>`; clearTopo(); clearFlow(); render(); return; }
topoColorMap = new Map(); r.levels.forEach((level, li) => { const pal = LAYER_PALETTE[li % LAYER_PALETTE.length]; for (const ni of level) { topoColorMap.set(nodes[ni].id, { ...pal, layer: li + 1 }); } });
let html = `<b>拓扑排序(共 ${r.levels.length} 层)</b>`;
r.levels.forEach((level, li) => { const pal = LAYER_PALETTE[li % LAYER_PALETTE.length];
const chips = level.map(ni => `<span class="chip" style="background:${pal.fill};color:${pal.text};border-color:${pal.stroke}">v${ni + 1}</span>` ).join('');
html += `<div class="topo-level"> <span class="lv-tag" style="background:${pal.stroke}">第 ${li + 1} 层</span> <span class="lv-nodes">${chips}</span> </div>`; });
html += `<div class="topo-note">同层顶点互不可达(不存在层内边);层号越靠前的顶点越先被处理。</div>`; html += `<div class="topo-note">同层顶点互不可达;层号越靠前越先被处理。</div>`;
algoResult.innerHTML = html; clearHighlight(); clearFlow(); clearHighlight(); clearFlow(); render(); }
function showPath() {11 行未改动 if (!r) { algoResult.innerHTML = '<span class="err">选择的顶点无效。</span>'; return; }
const sName = nameOf(sel.s), dName = nameOf(sel.d);
if (r.negativeCycle) { algoResult.innerHTML = `<b>${sName} → ${dName}</b><br>` + `<span class="neg">检测到负环:最短路径无定义(−∞)</span>` + `<br><span style="font-size:11.5px;color:#94a3b8">SPFA 检测到源点可达的负环,请修改边权或图结构。</span>`; clearHighlight(); render(); return; }
if (r.dist === Infinity) { algoResult.innerHTML = `${sName} → ${dName} 的最短路:<span class="inf">INF</span>(不可达)`; clearHighlight();5 行未改动 const edgeIds = new Set(); 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; const e = edges.find(e => (e.a === u && e.b === v) || (e.a === v && e.b === u)); if (e) edgeIds.add(e.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)) { const w = edgeCap(e); if (w < bestW) { bestW = w; best = e; } } } if (best) edgeIds.add(best.id); } highlight = { nodeIds, edgeIds };
const pathStr = r.path .map(i => `<span class="seq">v${i + 1}</span>`) .join('<span class="arrow">→</span>');
const distLabel = capEnabled ? `最短路径权重:<span class="k">${r.dist}</span>(按边权累加)` : `最短路长度:<span class="k">${r.dist}</span> 条边`; const distClass = r.dist < 0 ? 'neg' : 'k'; const algoName = directed ? 'SPFA' : 'Dijkstra';
let distLabel; if (capEnabled) { distLabel = `最短路径权重:<span class="${distClass}">${fmtNum(r.dist)}</span>` + ` <span style="color:#94a3b8;font-size:11px">(${algoName})</span>`; } else { distLabel = `最短路长度:<span class="k">${r.dist}</span> 条边`; }
algoResult.innerHTML = `<b>${sName} → ${dName}</b><br>` + `${distLabel}<br>` + `路径:${pathStr}`; `<b>${sName} → ${dName}</b><br>${distLabel}<br>路径:${pathStr}`;
render(); }
17 行未改动 clearFlow(); render(); return; }
flowHighlight = result.flowMap;
const sName = nameOf(sel.s), dName = nameOf(sel.d); const usedEdges = flowHighlight.size;
let extra = ''; if (!directed) extra += '<br><span style="color:#94a3b8;font-size:11.5px">(无向边双向容量各 = 边容量)</span>'; if (capEnabled) extra += '<br><span style="color:#94a3b8;font-size:11.5px">(按自定义容量计算)</span>'; if (capEnabled) extra += '<br><span style="color:#94a3b8;font-size:11.5px">(按自定义实数容量计算;负容量边与自环忽略)</span>'; else extra += '<br><span style="color:#94a3b8;font-size:11.5px">(所有边容量 = 1)</span>';
let flowInfo; if (usedEdges > 0) {4 行未改动 }
algoResult.innerHTML = `<b>${sName} → ${dName}</b><br>` + `最大流:<span class="k">${result.value}</span> 单位${extra}${flowInfo}`; `最大流:<span class="k">${fmtNum(result.value)}</span> 单位${extra}${flowInfo}`;
render(); }
/* ============================================================ * 手动增删 * 增删 * ============================================================ */ function setNodeCount(target) { target = clamp(target, 0, MAX_NODES);
while (nodes.length < target) { let best = { x: W / 2, y: H / 2 }, bestD = -1; for (let t = 0; t < 24; t++) { const x = NODE_R + 24 + Math.random() * Math.max(1, W - 2 * NODE_R - 48);3 行未改动 if (d > bestD) { bestD = d; best = { x, y }; } } nodes.push({ id: nodeSeq++, x: best.x, y: best.y, vx: 0, vy: 0 }); }
while (nodes.length > target) { const nd = nodes.pop(); edges = edges.filter(e => e.a !== nd.id && e.b !== nd.id); }
if (pending !== null && !nodes.some(n => n.id === pending)) pending = null; clearAllVisual(); refresh(); }
function setEdgeCount(target) { const n = nodes.length; const maxE = directed ? n * (n - 1) : n * (n - 1) / 2; target = clamp(target, 0, maxE);
if (target > edges.length) { const pool = []; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { const a = nodes[i].id, b = nodes[j].id; if (!hasEdge(a, b)) pool.push([a, b]); if (directed && !hasEdge(b, a)) pool.push([b, a]); const key = a < b ? `${a}-${b}` : `${b}-${a}`; const has = edges.some(e => { if (e.a === e.b) return false; const k = e.a < e.b ? `${e.a}-${e.b}` : `${e.b}-${e.a}`; return k === key; }); if (!has) pool.push([a, b]); if (directed && !edges.some(e => e.a === a && e.b === b)) pool.push([a, b]); } } shuffle(pool); for (const [a, b] of pool) { if (edges.length >= target) break; if (!hasEdge(a, b)) edges.push({ id: edgeSeq++, a, b, cap: 1 }); edges.push({ id: edgeSeq++, a, b, cap: 1 }); } } else if (target < edges.length) { const shuffled = shuffle(edges.slice()); const keep = new Set(shuffled.slice(0, target).map(e => e.id));25 行未改动 numNodesEl.value = n;
const wantTree = chkTree.checked; const wantConn = chkConn.checked;
const maxE = directed ? n * (n - 1) : n * (n - 1) / 2; const m = wantTree ? Math.max(0, n - 1) : clamp(parseInt(numEdgesEl.value, 10) || 0, 0, maxE);11 行未改动 edgeSeq = 1; const used = new Set(); const keyOf = (a, b) => directed ? `${a}>${b}` : (a < b ? `${a}-${b}` : `${b}-${a}`);
const addE = (a, b) => { if (a === b || a === undefined || b === undefined) return false; const k = keyOf(a, b); if (used.has(k)) return false; used.add(k); edges.push({ id: edgeSeq++, a, b, cap: 1 }); return true; };
const ids = nodes.map(nd => nd.id);
if (n > 1 && (wantTree || (wantConn && m >= n - 1))) { const perm = shuffle(ids.slice()); for (let i = 1; i < n; i++) { const p = Math.floor(Math.random() * i); const a = perm[p], b = perm[i]; if (directed && !wantTree) { if (Math.random() < 0.5) addE(a, b); else addE(b, a); } else { addE(a, b); } } else addE(a, b); } }
if (!wantTree) { const pool = []; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) {15 行未改动 wake(); }
/* ============================================================ * 代码模式:解析与应用 * 代码模式解析 * ============================================================ */ function parseCode(text) { const lines = text.split('\n') .map(l => l.trim())7 行未改动 const m = parseInt(firstParts[1], 10); if (!Number.isInteger(n) || !Number.isInteger(m)) throw new Error('n 和 m 必须是整数'); if (n < 0 || n > MAX_NODES) throw new Error(`顶点数必须在 0-${MAX_NODES} 之间`); if (m < 0) throw new Error('边数不能为负'); const maxE = directed ? n * (n - 1) : n * (n - 1) / 2; if (m > maxE) throw new Error(`${directed ? '有向图' : '无向图'}最多只能有 ${maxE} 条边`);
if (lines.length - 1 < m) { throw new Error(`需要 ${m} 行边数据,但只找到 ${lines.length - 1} 行`); }
let weighted = false; let hasNegative = false; let selfLoopCount = 0; const parsedEdges = []; const seen = new Set();
for (let i = 0; i < m; i++) { const lineNum = i + 2; const parts = lines[i + 1].split(/\s+/);6 行未改动 } if (u < 1 || u > n || v < 1 || v > n) { throw new Error(`第 ${lineNum} 行顶点编号超出范围 [1, ${n}]`); } if (u === v) { throw new Error(`第 ${lineNum} 行不能是自环(u = v)`); }
let w = 1; if (parts.length >= 3) { w = parseInt(parts[2], 10); if (!Number.isInteger(w) || w < 0) { throw new Error(`第 ${lineNum} 行边权必须是非负整数`); w = parseFloat(parts[2]); if (!Number.isFinite(w)) { throw new Error(`第 ${lineNum} 行边权必须是有效数字`); } if (w > 9999) throw new Error(`第 ${lineNum} 行边权不能超过 9999`); if (w < 0) { if (!directed) { throw new Error(`第 ${lineNum} 行:无向图不支持负权边(会形成负环)`); } if (w < -MAX_WEIGHT) { throw new Error(`第 ${lineNum} 行边权不能小于 -${MAX_WEIGHT}`); } hasNegative = true; } else if (w > MAX_WEIGHT) { throw new Error(`第 ${lineNum} 行边权不能超过 ${MAX_WEIGHT}`); } weighted = true; }
const key = directed ? `${u}>${v}` : (u < v ? `${u}-${v}` : `${v}-${u}`); if (seen.has(key)) { throw new Error(`第 ${lineNum} 行与之前的边重复`); } seen.add(key);
if (u === v) selfLoopCount++; parsedEdges.push({ u, v, w }); }
return { n, m, weighted, edges: parsedEdges }; return { n, m, weighted, hasNegative, selfLoopCount, edges: parsedEdges }; }
function applyCode() { try { const data = parseCode(codeInput.value);
/* 重置图 */ nodes = []; edges = []; nodeSeq = 1; edgeSeq = 1;
/* 创建 n 个顶点(id 从 1 到 n,与输入编号一致) */ for (let i = 0; i < data.n; i++) { nodes.push({ id: nodeSeq++, x: 0, y: 0, vx: 0, vy: 0 }); } layoutCircle();
/* 创建边 */ for (const e of data.edges) { edges.push({ id: edgeSeq++, a: e.u, b: e.v, cap: e.w }); }
/* 带权图自动启用容量 */ if (data.weighted && !capEnabled) { capEnabled = true; chkCap.checked = true; }
/* 清空视觉状态并应用 */ clearAllVisual(); pending = null;
/* 自动整理(空图不整理) */ if (nodes.length > 0) { tidyLayout(); wake(); } else { refresh(); }
codeStatus.className = 'code-status ok'; codeStatus.textContent = `✓ 已加载:${data.n} 个顶点,${data.m} 条边` + (data.weighted ? '(带权图,容量已启用)' : '') + (directed ? ' · 有向' : ' · 无向'); let msg = `✓ 已加载:${data.n} 个顶点,${data.m} 条边`; if (data.weighted) msg += '(带实数权,容量已启用)'; if (data.hasNegative) msg += ' · 含负权'; if (data.selfLoopCount > 0) msg += ` · ${data.selfLoopCount} 个自环`; msg += directed ? ' · 有向' : ' · 无向'; codeStatus.textContent = msg;
} catch (err) { codeStatus.className = 'code-status err'; codeStatus.textContent = '✗ ' + err.message; } }
function loadCodeSample() { const sampleDirected = `7 101 2 51 3 42 3 22 4 33 5 44 5 24 6 35 6 55 7 26 7 4`; const sampleUndirected = `6 71 2 32 3 23 4 44 5 15 6 21 6 52 5 3`; const sampleDirected = `7 111 1 1.51 2 5.51 2 -2.12 3 2.43 4 3.34 4 0.84 5 2.45 6 5.15 7 -2.86 7 4.92 4 1.2`; const sampleUndirected = `6 91 1 2.51 2 3.51 2 1.82 3 2.23 4 4.13 4 0.74 5 1.75 6 2.32 5 3.9`; codeInput.value = directed ? sampleDirected : sampleUndirected; codeStatus.className = 'code-status'; codeStatus.textContent = ''; }6 行未改动 codeStatus.textContent = ''; codeInput.focus(); });
/* Ctrl+Enter 应用 */ codeInput.addEventListener('keydown', e => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); applyCode();24 行未改动 } 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 { if (!hasEdge(pending, id)) { edges.push({ id: edgeSeq++, a: pending, b: id, cap: 1 }); edges.push({ id: edgeSeq++, a: pending, b: id, cap: 1 }); clearAllVisual(); } pending = null; clearAllVisual(); } hoverPt = pt; refresh();
23 行未改动 const nx = clamp(pt.x - drag.ox, NODE_R + 4, W - NODE_R - 4); const ny = clamp(pt.y - drag.oy, NODE_R + 4, H - NODE_R - 4);
if (physicsEnabled) { let vx = nx - nd.x; let vy = ny - nd.y; let vx = nx - nd.x, vy = ny - nd.y; const sp = Math.hypot(vx, vy); if (sp > PHYS.maxSpeed) { vx = vx / sp * PHYS.maxSpeed; vy = vy / sp * PHYS.maxSpeed; } nd.vx = vx; nd.vy = vy; nd.x = nx; nd.y = ny; nd.vx = vx; nd.vy = vy; nd.x = nx; nd.y = ny; wake(); } else { nd.x = nx; nd.y = ny; nd.x = nx; nd.y = ny; nd.vx = 0; nd.vy = 0; scheduleRender(); } return;10 行未改动 drag = null; if (physicsEnabled) wake(); else updateUI(); }
if (blankDown) { const pt = svgPoint(e); if (Math.hypot(pt.x - blankDown.x, pt.y - blankDown.y) < 6) { if (nodes.length < MAX_NODES) {14 行未改动 });
window.addEventListener('pointercancel', () => { drag = null; blankDown = null; });
/* 右键:编辑边容量 / 删除边 */ svg.addEventListener('contextmenu', e => { e.preventDefault(); if (!capEnabled) return;
const edgeEl = e.target.closest ? e.target.closest('[data-edge]') : null; if (!edgeEl) { closePopup(); return; }
const edgeId = Number(edgeEl.dataset.edge); const edge = edges.find(x => x.id === edgeId); if (!edge) return;
openPopup(edge, e.clientX, e.clientY); });
/* ============================================================4 行未改动 if (!btn) return; document.querySelectorAll('#typeSeg .seg-btn').forEach(b => b.classList.remove('active')); 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; } } if (fixed) { algoResult.innerHTML = '<span class="err">切换到无向图后,原有的负权边已被置为 0。</span>'; } }
pending = null; clearAllVisual(); refresh(); });
const HINTS = { drag: '拖动顶点调整位置;在空白处单击可新增顶点。松手后顶点会带有惯性并相互弹开。', edge: '依次点击两个顶点添加一条边;再次点击同一点可取消选择。', edge: '依次点击两个顶点添加边;再次点击同一点可添加自环。允许重边(多次点击同一对顶点)。', erase: '点击顶点或边将其删除(删除顶点会同时删除其所有连边)。' }; document.getElementById('modeSeg').addEventListener('click', e => { const btn = e.target.closest('.seg-btn');7 行未改动 });
chkPhysics.addEventListener('change', () => { physicsEnabled = chkPhysics.checked; if (physicsEnabled) { wake(); } else { if (physicsEnabled) wake(); else { nodes.forEach(nd => { nd.vx = 0; nd.vy = 0; }); updateUI(); } updateUI();82 行未改动 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 行未改动