版本比较
图-查看器
正文
增加 872 行删除 291 行
17 行未改动1819202122222423242526275 行未改动33343536373839404142434445464748495051525334 行未改动8889909180929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215314 行未改动16816917017110317217317417517617717817918018118218318420 行未改动20520620720814020921021121221321421521621715021821922022115522222322422522610 行未改动23723823924017424124224324424517 行未改动2632642652662002672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243258 行未改动33433533633722633833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139234 行未改动4274284294302774314324334344356 行未改动44244344444529229329444644744844945045145223 行未改动4764774784794804814824834844854864873314884894904914926 行未改动4995005015023465035045055065075085093525105115125135144 行未改动5195205215225235245255265275285295305315325333693703715345355365375385395405415425435445455465475485495505515525535545555565578 行未改动56656756856939339439539639739857057140157257357457557657757857958058158258358441058558641258758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870941771071141971271371471542342442542642771671771871942943043143243372072172272372472572672772844344472973073173244744844945045145245345445573373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377446777546947077677777877978078178247278378478578678778878922 行未改动81281381481550350481681781881982082182282382482513 行未改动8398408418425268438448458469 行未改动8568578588598608618628638647 行未改动87287387487587687787887988088188256288388488588688788888989089189289389489589689789889956756890090190290390457290590657557690790890991091158058191291391491591691791891992058792192292392492592659492792892959793059960060193193293393493593660360460560660760860961061161261361461561693793893994094194294394494594694794894995061962062195195295395495595662595795862795996096196296396463396596696796896997097197264164297397497597697797816 行未改动995996997998667668669670671999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102167610221023102410251026102710281029103068610311032103310341035103610371038695696697698699700701103910401041104210431044104570 行未改动1116111711181119780112011211122112311241125112611277897907911128112911301131113245 行未改动1178117911801181118211831184118511861187118811891190845846847119111921193119411951196119711987 行未改动1206120712081209863121012111212121312141215121612171218121932 行未改动12521253125412551256125712581259126012611262126312641265126690512671268126912709091271127212731274127512761277916127812791280128112821283128492212851286925128712881289928129012911292129312 行未改动13061307130813091310131113121313131413151316131713183 行未改动13221323132413259601326132713289649659661329133013319701332972133313341335133613371338133998098198298398498598698713401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014217 行未改动14291430143114321433143414351436143714381439144014411014144214431444144514467 行未改动1454145514561457103010311032145814591460146114621463146414651040146614671468146910 行未改动14801481148214831059148414851486106314871488148914906 行未改动1497149814991500107810791080108110821083150115021503150410851505150615071508109015091510151115125 行未改动1518151915201521110415221523110715241525111011111112111311141115152615271528152915301531153215331123153415351536153715381129153915401132113315411134154215431137154415451140154615471548114415491550155115526 行未改动155915601561156215631564156515661162156715681569157011671571157215731574157515761577117511761177117815781579158015811182158215831185158415851586158715881589119211931590119415911592119715931594120015951596159715989 行未改动1608160916101611121816121220161316141615161616171226122712281618161916201621162216231624162512331234123516261236162716281629124016301631163216331634163516361637124916381251125212531639164016411642164313 行未改动16571658165916601275166116621663127916641665166616671668166916701671167216731289129012911292167416751676167712961297167816791680168113011302168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617075 行未改动1713171417151716132917171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741350135113521353177517761777177817791780178117821783178417851786136513661367136813691370178717881789179017911792179317941795179613791797179817991800138118011802180318041805180618071388180818091810181118126 行未改动181918201821182218231824182518261827182818291830183114111832141318331834141618351836183718381839142118401423142414251426142718411842184318441845184618478 行未改动185618571858185914441860186118621863186418651451186618671868186918701871187214591873146118741875146418761877187814681879188018811882188314741475188414761885147814791886188718881889189011 行未改动1902190319041905190619071908190919101911191219131914191519161917191819195 行未改动1925192619271928151215131514192919301931193219331934193519361937193819391940194119421943194419451522152315241946194719481949195019511952195319541955195619571527152815291958195919601961196217 行未改动19801981198219831555198419851986198719881561198919901991199219934 行未改动1998199920002001157420022003200420052006200715802008200920102011158420122013201420153 行未改动201920202021202215962023202420252026160120272028202920302031203220332034203516112036203720382039204016171618204120422043204420452046204720482049205020512052205316242054205520562057205825 行未改动20842085208620871658208820892090209111 行未改动210321042105210616782107210821092110211121122113211416872115211621172118211921202121212221231697169816992124212521261702212721282129213015 行未改动2146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230916 行未改动232623272328232923302331233223331752175323341754175523352336233723382339234023 行未改动23642365236623671788178923682369237023712372237317951796179717982374237523762377180118022378237923802381238210 行未改动23932394239523961821239723982399240014 行未改动2415241624172418184418451846241924201849185024211851242224231854242424252426185824272428242924304 行未改动2435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724581878245924602461246224637 行未改动247124722473247418941895189624752476247724782479248082 行未改动2563256425652566256725682569257025712 行未改动17 行未改动 -webkit-font-smoothing:antialiased; } .app{display:flex;height:100vh;}
/* ================= 侧栏 ================= */ .panel{ width:340px;flex:0 0 340px;background:#fff;border-right:1px solid var(--border); 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; } .panel h1{font-size:17px;margin:0 0 4px;letter-spacing:.3px;display:flex;align-items:center;gap:8px;} .panel h1::before{5 行未改动 font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:var(--muted); margin:0 0 10px;font-weight:700; }
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; } details.card summary::-webkit-details-marker{display:none;} details.card summary::before{ content:"▶";font-size:9px;color:#64748b; transition:transform .18s ease;display:inline-block; } details.card[open] summary::before{transform:rotate(90deg);} details.card[open] summary{border-bottom:1px solid var(--border);border-radius:12px 12px 0 0;margin-bottom:10px;}
.seg{display:flex;background:#e2e8f0;border-radius:9px;padding:3px;gap:3px;} .seg-btn{ flex:1;border:0;background:transparent;padding:7px 4px;border-radius:7px; font-size:13px;cursor:pointer;color:#475569;font-family:inherit;font-weight:500;transition:.15s;34 行未改动 .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);17 行未改动</head><body><div class="app"> <aside class="panel"> <h1>图论可视化</h1> <h1>图论可视化 2D</h1>
<section class="card"> <h2>图类型</h2> <div class="seg" id="typeSeg"> <button class="seg-btn active" data-type="undirected">无向图</button> <button class="seg-btn" data-type="directed">有向图</button> </div> </section>
<details class="card" id="codeCard"> <summary>📝 代码模式</summary> <div> <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> <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 91 1 21 2 2.51 2 3.71 3 3.142 3 0.52 4 1.23 5 4.84 5 35 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' },23 行未改动 const selDst = document.getElementById('selDst'); const edgePopup = document.getElementById('edgePopup'); 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)); }
/* 边的有效容量:开启容量模式时使用存储值,否则为 1 */ 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(); }13 行未改动 if (e.key === 'Enter') { e.preventDefault(); savePopup(); } else if (e.key === 'Escape') { e.preventDefault(); closePopup(); } });
/* 点击弹窗外部自动关闭 */ document.addEventListener('pointerdown', e => { if (edgePopup.style.display === 'block' && !edgePopup.contains(e.target)) { closePopup(); }9 行未改动 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}"` : ''}/>`;
/* 有流量的边:叠加半透明蓝色底层高亮 */ if (hasFlow) { html += `<path d="${d}" fill="none" stroke="rgba(59,130,246,0.35)" 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; }16 行未改动 stroke="rgba(37,99,235,0.95)" stroke-width="1.4" stroke-linejoin="round" pointer-events="none"/>`;
if (info.amount > 1) { html += `<text x="${mid.x + px * 17}" y="${mid.y + py * 17}" text-anchor="middle" dominant-baseline="central" font-size="11" font-weight="700" fill="#1d4ed8" pointer-events="none" font-family="ui-monospace,Menlo,monospace">${info.amount}</text>`; 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 = 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="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() { const r = analyze();
if (r.n === 0) { analysisEl.innerHTML = `<p class="empty">画布为空。请设置顶点数后点击「随机生成」,或直接在空白处单击添加顶点。</p>`; `<p class="empty">画布为空。请设置顶点数后点击「随机生成」,或在代码模式中粘贴数据。</p>`; return; }
const badge = (ok, yes, no) => `<span class="badge ${ok ? 'yes' : 'no'}">${ok ? yes : no}</span>`;
let html = `<div class="stats">12 行未改动 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) => {3 行未改动 html += `<span class="deg">v${i + 1} : ${r.degU[i]}</span>`; } }); 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('');
selSrc.innerHTML = opts || '<option value="">—</option>'; selDst.innerHTML = opts || '<option value="">—</option>';
const hasSrc = nodes.some(nd => String(nd.id) === oldSrc); selSrc.value = hasSrc ? oldSrc : (nodes.length ? String(nodes[0].id) : '');
const hasDst = nodes.some(nd => String(nd.id) === oldDst); if (hasDst) { selDst.value = oldDst; } else if (nodes.length > 1) { selDst.value = String(nodes[nodes.length - 1].id); } else if (nodes.length === 1) { selDst.value = String(nodes[0].id); } else { selDst.value = ''; if (hasDst) selDst.value = oldDst; else if (nodes.length > 1) selDst.value = String(nodes[nodes.length - 1].id); 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(); }
/* ============================================================ * 图算法核心 * ============================================================ */
/* ---------- 拓扑排序(Kahn,按层返回) ---------- */ 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 }; }
/* ---------- 最短路(Dijkstra,权重 = 边容量) ---------- */ 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 }; }
/* ---------- 最大流(Edmonds-Karp,容量 = 边容量) ---------- * 返回 { value, flowMap } * flowMap: Map<edgeId, { dir: 'a→b' | 'b→a', amount: number }> */ 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; 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()) .filter(l => l && !l.startsWith('#'));
if (lines.length === 0) throw new Error('输入为空');
const firstParts = lines[0].split(/\s+/); if (firstParts.length < 2) throw new Error('第一行必须是 "n m" 格式'); const n = parseInt(firstParts[0], 10); 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('边数不能为负');
if (lines.length - 1 < m) { throw new Error(`需要 ${m} 行边数据,但只找到 ${lines.length - 1} 行`); }
let weighted = false; let hasNegative = false; let selfLoopCount = 0; const parsedEdges = [];
for (let i = 0; i < m; i++) { const lineNum = i + 2; const parts = lines[i + 1].split(/\s+/); if (parts.length < 2) throw new Error(`第 ${lineNum} 行格式错误:至少需要两个整数`);
const u = parseInt(parts[0], 10); const v = parseInt(parts[1], 10); if (!Number.isInteger(u) || !Number.isInteger(v)) { throw new Error(`第 ${lineNum} 行顶点编号必须是整数`); } 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]); if (!Number.isFinite(w)) { throw new Error(`第 ${lineNum} 行边权必须是有效数字`); } 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; }
if (u === v) selfLoopCount++; parsedEdges.push({ u, v, w }); }
return { n, m, weighted, hasNegative, selfLoopCount, edges: parsedEdges }; }
function applyCode() { try { const data = parseCode(codeInput.value);
nodes = []; edges = []; nodeSeq = 1; edgeSeq = 1;
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'; 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 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 = ''; }
document.getElementById('btnCodeApply').addEventListener('click', applyCode); document.getElementById('btnCodeSample').addEventListener('click', loadCodeSample); document.getElementById('btnCodeClear').addEventListener('click', () => { codeInput.value = ''; codeStatus.className = 'code-status'; codeStatus.textContent = ''; codeInput.focus(); });
codeInput.addEventListener('keydown', e => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); applyCode(); } });
/* ============================================================ * 指针交互 * ============================================================ */ svg.addEventListener('pointerdown', e => { if (e.pointerType === 'mouse' && e.button !== 0) return;16 行未改动 } 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; // 容量模式未启用,不做任何事 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 行未改动