-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMSTControl.cs
More file actions
373 lines (317 loc) · 13.8 KB
/
MSTControl.cs
File metadata and controls
373 lines (317 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1
{
public class MSTControl : BaseGraphControl
{
private Button btnGenerate;
private Button btnRun;
private Button btnReset;
private Button btnSave;
private Button btnLoad;
private Button btnAddNode;
private Button btnAddEdge;
private Button btnMoveNode;
private Button btnCancelMode;
private NumericUpDown numNodes;
private Label lblResult;
private Label lblMode;
private EditMode currentMode = EditMode.None;
private enum EditMode { None, AddNode, AddEdge, MoveNode }
public MSTControl() : base()
{
graph = new WeightedGraph(false);
InitializeControls();
}
private void InitializeControls()
{
var flowPanel = new FlowLayoutPanel
{
Dock = DockStyle.Fill,
FlowDirection = FlowDirection.TopDown,
WrapContents = false,
AutoScroll = true,
Padding = new Padding(5)
};
var titleLabel = CreateLabel("Алгоритм Прима (MST)", true, 11);
titleLabel.ForeColor = Color.DarkGreen;
flowPanel.Controls.Add(titleLabel);
flowPanel.Controls.Add(new Label { Height = 5 });
var genPanel = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, AutoSize = true };
genPanel.Controls.Add(CreateLabel("Узлы:"));
numNodes = new NumericUpDown { Width = 55, Minimum = 4, Maximum = 12, Value = 6 };
genPanel.Controls.Add(numNodes);
btnGenerate = CreateButton("🎲 Генерировать", Color.LightBlue, (s, e) => GenerateGraph());
genPanel.Controls.Add(btnGenerate);
flowPanel.Controls.Add(genPanel);
flowPanel.Controls.Add(new Label { Height = 10 });
flowPanel.Controls.Add(CreateLabel("Редактирование:", true, 10));
var editPanel = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, AutoSize = true };
btnAddNode = CreateButton("+ Узел", Color.LightGreen, (s, e) => SetMode(EditMode.AddNode));
btnAddNode.Width = 80;
btnAddEdge = CreateButton("+ Ребро", Color.LightYellow, (s, e) => SetMode(EditMode.AddEdge));
btnAddEdge.Width = 80;
btnMoveNode = CreateButton("✋ Двигать", Color.LightSkyBlue, (s, e) => SetMode(EditMode.MoveNode));
btnMoveNode.Width = 80;
editPanel.Controls.AddRange(new Control[] { btnAddNode, btnAddEdge, btnMoveNode });
flowPanel.Controls.Add(editPanel);
lblMode = new Label
{
Text = "Режим: просмотр",
AutoSize = true,
ForeColor = Color.DarkBlue,
Font = new Font("Segoe UI", 9, FontStyle.Italic),
MaximumSize = new Size(250, 0)
};
flowPanel.Controls.Add(lblMode);
btnCancelMode = CreateButton("↩ Отмена режима", Color.Gainsboro, (s, e) => SetMode(EditMode.None));
flowPanel.Controls.Add(btnCancelMode);
flowPanel.Controls.Add(new Label { Height = 10 });
var lblSpeed = CreateLabel("Скорость анимации: 500мс");
flowPanel.Controls.Add(lblSpeed);
flowPanel.Controls.Add(CreateSpeedTrackBar(lblSpeed));
flowPanel.Controls.Add(new Label { Height = 10 });
btnRun = CreateButton("▶ Построить MST", Color.ForestGreen, async (s, e) => await RunPrim());
btnRun.ForeColor = Color.White;
btnRun.Width = 180;
btnRun.Height = 38;
btnRun.Font = new Font("Segoe UI", 10, FontStyle.Bold);
flowPanel.Controls.Add(btnRun);
lblResult = new Label
{
Text = "Вес MST: —",
AutoSize = true,
Font = new Font("Segoe UI", 10, FontStyle.Bold),
ForeColor = Color.DarkGreen
};
flowPanel.Controls.Add(lblResult);
flowPanel.Controls.Add(new Label { Height = 10 });
btnReset = CreateButton("🔄 Сбросить", Color.Silver, (s, e) => ResetGraph());
flowPanel.Controls.Add(btnReset);
flowPanel.Controls.Add(new Label { Height = 15 });
flowPanel.Controls.Add(CreateLabel("Файлы:", true, 10));
var filePanel = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, AutoSize = true };
btnSave = CreateButton("💾 Сохранить", Color.LightSteelBlue, (s, e) => SaveGraph());
btnSave.Width = 115;
btnLoad = CreateButton("📂 Загрузить", Color.LightSteelBlue, (s, e) => LoadGraph());
btnLoad.Width = 115;
filePanel.Controls.AddRange(new Control[] { btnSave, btnLoad });
flowPanel.Controls.Add(filePanel);
controlPanel.Controls.Add(flowPanel);
}
private void SetMode(EditMode mode)
{
currentMode = mode;
selectedNode = null;
isDragging = false;
draggingNode = null;
lblMode.Text = mode switch
{
EditMode.AddNode => "Режим: добавление узла",
EditMode.AddEdge => "Режим: добавление ребра",
EditMode.MoveNode => "Режим: перемещение узлов",
_ => "Режим: просмотр"
};
lblMode.ForeColor = mode == EditMode.None ? Color.DarkBlue : Color.DarkRed;
drawPanel.Cursor = mode == EditMode.MoveNode ? Cursors.SizeAll : Cursors.Default;
RefreshGraph();
}
private void GenerateGraph()
{
graph = new WeightedGraph(false);
int n = (int)numNodes.Value;
graph.GenerateRandom(n, n * 2, drawPanel.Width, drawPanel.Height, 1, 15);
Log($"Сгенерирован граф: {graph.Nodes.Count} узлов, {graph.Edges.Count} рёбер");
UpdateMatrix();
RefreshGraph();
}
private void ResetGraph()
{
graph.ResetState();
lblResult.Text = "Вес MST: —";
SetMode(EditMode.None);
RefreshGraph();
}
protected override void DrawPanel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(Color.White);
GraphRenderer.DrawGraph(e.Graphics, graph, selectedNode, showWeights: true);
var legend = new Dictionary<Color, string>
{
{ Color.LightBlue, "Не в дереве" },
{ Color.Yellow, "Кандидат" },
{ Color.Green, "В MST" }
};
GraphRenderer.DrawLegend(e.Graphics, legend);
}
protected override void OnMouseDownHandler(MouseEventArgs e)
{
var clickedNode = FindNodeAtPosition(e.Location);
switch (currentMode)
{
case EditMode.AddNode:
if (clickedNode == null)
{
graph.AddNode(e.Location);
Log($"Добавлен узел {graph.Nodes.Count - 1}");
UpdateMatrix();
RefreshGraph();
}
break;
case EditMode.AddEdge:
if (clickedNode != null)
{
if (selectedNode == null)
{
selectedNode = clickedNode;
lblMode.Text = $"Выбран узел {clickedNode.Id}\nКликните на второй";
}
else if (clickedNode != selectedNode)
{
string input = ShowInputDialog("Введите вес ребра:", "Вес", "1");
if (!string.IsNullOrEmpty(input) && int.TryParse(input, out int weight) && weight > 0)
{
graph.AddEdge(selectedNode, clickedNode, weight);
Log($"Добавлено ребро {selectedNode.Id} — {clickedNode.Id} (вес: {weight})");
UpdateMatrix();
}
selectedNode = null;
lblMode.Text = "Режим: добавление ребра";
RefreshGraph();
}
}
break;
case EditMode.MoveNode:
if (clickedNode != null)
{
StartDragging(clickedNode, e.Location);
}
break;
default:
selectedNode = clickedNode;
RefreshGraph();
break;
}
}
protected override void DrawPanel_MouseMove(object sender, MouseEventArgs e)
{
if (isRunning) return;
if (currentMode == EditMode.MoveNode && isDragging && draggingNode != null)
{
int newX = e.X - dragOffset.X;
int newY = e.Y - dragOffset.Y;
int margin = 30;
newX = Math.Max(margin, Math.Min(drawPanel.Width - margin, newX));
newY = Math.Max(margin, Math.Min(drawPanel.Height - margin, newY));
draggingNode.Position = new Point(newX, newY);
RefreshGraph();
}
else if (currentMode == EditMode.MoveNode)
{
var node = FindNodeAtPosition(e.Location);
drawPanel.Cursor = node != null ? Cursors.SizeAll : Cursors.Hand;
}
}
protected override void DrawPanel_MouseUp(object sender, MouseEventArgs e)
{
if (currentMode == EditMode.MoveNode && isDragging && draggingNode != null)
{
Log($"Узел {draggingNode.Id} перемещён");
isDragging = false;
draggingNode = null;
RefreshGraph();
}
}
private async Task RunPrim()
{
if (graph.Nodes.Count < 2)
{
MessageBox.Show("Нужно минимум 2 узла!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
isRunning = true;
SetButtonsEnabled(false);
graph.ResetState();
Log("\n=== Алгоритм Прима ===");
int totalWeight = await PrimAlgorithm();
lblResult.Text = $"Вес MST: {totalWeight}";
Log($"=== Общий вес MST = {totalWeight} ===\n");
isRunning = false;
SetButtonsEnabled(true);
}
private async Task<int> PrimAlgorithm()
{
int n = graph.Nodes.Count;
int[] key = new int[n];
int[] parent = new int[n];
bool[] inMST = new bool[n];
for (int i = 0; i < n; i++)
{
key[i] = int.MaxValue;
parent[i] = -1;
}
key[0] = 0;
int totalWeight = 0;
Log("Начинаем с узла 0");
graph.Nodes[0].Color = Color.Green;
RefreshGraph();
await Task.Delay(animationDelay);
for (int count = 0; count < n; count++)
{
int u = -1;
int minKey = int.MaxValue;
for (int v = 0; v < n; v++)
{
if (!inMST[v] && key[v] < minKey)
{
minKey = key[v];
u = v;
}
}
if (u == -1) break;
inMST[u] = true;
graph.Nodes[u].Color = Color.Green;
if (parent[u] != -1)
{
var edge = graph.GetEdge(graph.Nodes[parent[u]], graph.Nodes[u]);
if (edge != null)
{
edge.IsInResult = true;
totalWeight += edge.Weight;
}
Log($"Добавлено ребро {parent[u]} — {u} (вес: {key[u]}). Итого: {totalWeight}");
}
RefreshGraph();
await Task.Delay(animationDelay);
foreach (var neighbor in graph.GetNeighbors(graph.Nodes[u]))
{
int v = neighbor.Id;
int weight = graph.GetWeight(graph.Nodes[u], neighbor);
if (!inMST[v] && weight < key[v])
{
key[v] = weight;
parent[v] = u;
neighbor.Color = Color.Yellow;
Log($" Обновлён ключ узла {v}: {weight}");
}
}
RefreshGraph();
await Task.Delay(animationDelay / 2);
}
return totalWeight;
}
private void SetButtonsEnabled(bool enabled)
{
btnRun.Enabled = enabled;
btnGenerate.Enabled = enabled;
btnAddNode.Enabled = enabled;
btnAddEdge.Enabled = enabled;
btnMoveNode.Enabled = enabled;
btnSave.Enabled = enabled;
btnLoad.Enabled = enabled;
}
}
}