-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphTraversalControl.cs
More file actions
426 lines (364 loc) · 17 KB
/
GraphTraversalControl.cs
File metadata and controls
426 lines (364 loc) · 17 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1
{
public class GraphTraversalControl : BaseGraphControl
{
private Button btnGenerateGraph;
private Button btnDFS;
private Button btnBFS;
private Button btnReset;
private Button btnSave;
private Button btnLoad;
private Button btnAddNode;
private Button btnAddEdge;
private Button btnDeleteNode;
private Button btnMoveNode;
private Button btnCancelMode;
private NumericUpDown numNodes;
private NumericUpDown numEdges;
private Label lblMode;
private WeightedGraph.Node edgeStartNode = null;
private EditMode currentMode = EditMode.None;
private enum EditMode { None, AddNode, AddEdge, DeleteNode, MoveNode }
public GraphTraversalControl() : 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)
};
// === Генерация ===
flowPanel.Controls.Add(CreateLabel("Генерация графа:", true, 10));
var genPanel = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, AutoSize = true };
genPanel.Controls.Add(CreateLabel("Узлы:"));
numNodes = new NumericUpDown { Width = 55, Minimum = 3, Maximum = 15, Value = 6 };
genPanel.Controls.Add(numNodes);
genPanel.Controls.Add(CreateLabel("Рёбра:"));
numEdges = new NumericUpDown { Width = 55, Minimum = 3, Maximum = 30, Value = 8 };
genPanel.Controls.Add(numEdges);
flowPanel.Controls.Add(genPanel);
btnGenerateGraph = CreateButton("🎲 Генерировать", Color.LightBlue, (s, e) => GenerateGraph());
flowPanel.Controls.Add(btnGenerateGraph);
flowPanel.Controls.Add(new Label { Height = 10 });
// === Редактирование ===
flowPanel.Controls.Add(CreateLabel("Редактирование:", true, 10));
var editPanel1 = 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;
btnDeleteNode = CreateButton("✕ Удалить", Color.LightCoral, (s, e) => SetMode(EditMode.DeleteNode));
btnDeleteNode.Width = 80;
editPanel1.Controls.AddRange(new Control[] { btnAddNode, btnAddEdge, btnDeleteNode });
flowPanel.Controls.Add(editPanel1);
var editPanel2 = new FlowLayoutPanel { FlowDirection = FlowDirection.LeftToRight, AutoSize = true };
btnMoveNode = CreateButton("✋ Переместить", Color.LightSkyBlue, (s, e) => SetMode(EditMode.MoveNode));
btnMoveNode.Width = 120;
editPanel2.Controls.Add(btnMoveNode);
flowPanel.Controls.Add(editPanel2);
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 });
// === Алгоритмы ===
flowPanel.Controls.Add(CreateLabel("Алгоритмы обхода:", true, 10));
btnDFS = CreateButton("▶ DFS (Глубина)", Color.MediumSeaGreen, async (s, e) => await RunTraversal(true));
btnDFS.ForeColor = Color.White;
btnDFS.Width = 145;
flowPanel.Controls.Add(btnDFS);
btnBFS = CreateButton("▶ BFS (Ширина)", Color.RoyalBlue, async (s, e) => await RunTraversal(false));
btnBFS.ForeColor = Color.White;
btnBFS.Width = 145;
flowPanel.Controls.Add(btnBFS);
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);
flowPanel.Controls.Add(new Label { Height = 15 });
var infoLabel = new Label
{
Text = "ℹ DFS использует СТЕК\n" +
" BFS использует ОЧЕРЕДЬ\n" +
" Сложность: O(V + E)",
AutoSize = true,
ForeColor = Color.DarkSlateGray,
Font = new Font("Segoe UI", 8.5f)
};
flowPanel.Controls.Add(infoLabel);
controlPanel.Controls.Add(flowPanel);
}
private void SetMode(EditMode mode)
{
currentMode = mode;
edgeStartNode = null;
selectedNode = null;
isDragging = false;
draggingNode = null;
lblMode.Text = mode switch
{
EditMode.AddNode => "Режим: добавление узла\n(кликните на пустое место)",
EditMode.AddEdge => "Режим: добавление ребра\n(выберите 2 узла)",
EditMode.DeleteNode => "Режим: удаление\n(кликните на узел)",
EditMode.MoveNode => "Режим: перемещение\n(перетащите узел)",
_ => "Режим: просмотр"
};
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);
graph.GenerateRandom((int)numNodes.Value, (int)numEdges.Value,
drawPanel.Width, drawPanel.Height, 1, 10);
Log($"Сгенерирован граф: {graph.Nodes.Count} узлов, {graph.Edges.Count} рёбер");
UpdateMatrix();
RefreshGraph();
}
private void ResetGraph()
{
graph.ResetState();
SetMode(EditMode.None);
RefreshGraph();
Log("Граф сброшен");
}
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.Red, "Обрабатывается" },
{ Color.Green, "Обработан" }
};
GraphRenderer.DrawLegend(e.Graphics, legend);
}
protected override void OnMouseDownHandler(MouseEventArgs e)
{
Point clickPos = e.Location;
WeightedGraph.Node clickedNode = FindNodeAtPosition(clickPos);
switch (currentMode)
{
case EditMode.AddNode:
if (clickedNode == null)
{
graph.AddNode(clickPos);
Log($"Добавлен узел {graph.Nodes.Count - 1}");
UpdateMatrix();
RefreshGraph();
}
break;
case EditMode.AddEdge:
if (clickedNode != null)
{
if (edgeStartNode == null)
{
edgeStartNode = clickedNode;
selectedNode = clickedNode;
lblMode.Text = $"Выбран узел {clickedNode.Id}\nКликните на второй узел";
RefreshGraph();
}
else if (clickedNode != edgeStartNode)
{
string input = ShowInputDialog("Введите вес ребра:", "Вес ребра", "1");
if (!string.IsNullOrEmpty(input) && int.TryParse(input, out int weight) && weight > 0)
{
graph.AddEdge(edgeStartNode, clickedNode, weight);
Log($"Добавлено ребро {edgeStartNode.Id} — {clickedNode.Id} (вес: {weight})");
UpdateMatrix();
}
edgeStartNode = null;
selectedNode = null;
lblMode.Text = "Режим: добавление ребра\n(выберите 2 узла)";
RefreshGraph();
}
}
break;
case EditMode.DeleteNode:
if (clickedNode != null)
{
int id = clickedNode.Id;
graph.RemoveNode(clickedNode);
Log($"Узел {id} удалён");
UpdateMatrix();
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 RunTraversal(bool isDFS)
{
if (graph.Nodes.Count == 0)
{
MessageBox.Show("Сначала создайте граф!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
isRunning = true;
SetButtonsEnabled(false);
graph.ResetState();
string algoName = isDFS ? "DFS" : "BFS";
Log($"\n=== Начало {algoName} ===");
var startNode = graph.Nodes[0];
List<int> visitOrder = new List<int>();
if (isDFS)
{
Stack<WeightedGraph.Node> stack = new Stack<WeightedGraph.Node>();
stack.Push(startNode);
while (stack.Count > 0)
{
var current = stack.Pop();
if (current.Visited) continue;
current.Visited = true;
current.Color = Color.Red;
visitOrder.Add(current.Id);
Log($"DFS: Посещён узел {current.Id}. Стек: [{GetCollectionContent(stack)}]");
RefreshGraph();
await Task.Delay(animationDelay);
foreach (var neighbor in graph.GetNeighbors(current))
{
if (!neighbor.Visited)
{
stack.Push(neighbor);
if (neighbor.Color == Color.LightBlue)
neighbor.Color = Color.Yellow;
}
}
RefreshGraph();
await Task.Delay(animationDelay / 2);
current.Color = Color.Green;
RefreshGraph();
}
}
else
{
Queue<WeightedGraph.Node> queue = new Queue<WeightedGraph.Node>();
queue.Enqueue(startNode);
startNode.Visited = true;
startNode.Color = Color.Yellow;
while (queue.Count > 0)
{
var current = queue.Dequeue();
current.Color = Color.Red;
visitOrder.Add(current.Id);
Log($"BFS: Обрабатывается узел {current.Id}. Очередь: [{GetCollectionContent(queue)}]");
RefreshGraph();
await Task.Delay(animationDelay);
foreach (var neighbor in graph.GetNeighbors(current))
{
if (!neighbor.Visited)
{
neighbor.Visited = true;
neighbor.Color = Color.Yellow;
queue.Enqueue(neighbor);
}
}
RefreshGraph();
await Task.Delay(animationDelay / 2);
current.Color = Color.Green;
RefreshGraph();
}
}
Log($"=== {algoName} завершён. Порядок: {string.Join(" → ", visitOrder)} ===\n");
isRunning = false;
SetButtonsEnabled(true);
}
private string GetCollectionContent<T>(IEnumerable<T> collection) where T : WeightedGraph.Node
{
var ids = new List<int>();
foreach (var node in collection)
ids.Add(node.Id);
return string.Join(", ", ids);
}
private void SetButtonsEnabled(bool enabled)
{
btnDFS.Enabled = enabled;
btnBFS.Enabled = enabled;
btnGenerateGraph.Enabled = enabled;
btnAddNode.Enabled = enabled;
btnAddEdge.Enabled = enabled;
btnDeleteNode.Enabled = enabled;
btnMoveNode.Enabled = enabled;
btnSave.Enabled = enabled;
btnLoad.Enabled = enabled;
}
}
}