Main
This commit is contained in:
Dvurechensky 2024-10-05 09:04:42 +03:00
commit c6522b97c6
9 changed files with 236 additions and 0 deletions

2
.gitattributes vendored Normal file

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

3
.gitignore vendored Normal file

@ -0,0 +1,3 @@
.vs
GrufCustom/bin
GrufCustom/obj

25
GrufCustom.sln Normal file

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32616.157
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GrafCustom", "GrufCustom\GrafCustom.csproj", "{855A04E3-8F24-4879-ABD9-CECA260A7645}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{855A04E3-8F24-4879-ABD9-CECA260A7645}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{855A04E3-8F24-4879-ABD9-CECA260A7645}.Debug|Any CPU.Build.0 = Debug|Any CPU
{855A04E3-8F24-4879-ABD9-CECA260A7645}.Release|Any CPU.ActiveCfg = Release|Any CPU
{855A04E3-8F24-4879-ABD9-CECA260A7645}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {550B1FB8-6683-4CE5-86D1-D61F88AF51B9}
EndGlobalSection
EndGlobal

22
GrufCustom/Data/Edge.cs Normal file

@ -0,0 +1,22 @@
namespace GraphCustomSearcher.Data;
/// <summary>
/// Шаблог ребра
/// </summary>
public class Edge
{
/// <summary>
/// Узел начала
/// </summary>
public Verticle VerticleStart { get; set; }
/// <summary>
/// Узел конца
/// </summary>
public Verticle VerticleStop { get; set; }
public Edge(Verticle verticleStart, Verticle verticleStop)
{
VerticleStart = verticleStart;
VerticleStop = verticleStop;
}
}

@ -0,0 +1,21 @@
namespace GraphCustomSearcher.Data;
/// <summary>
/// Узел
/// </summary>
public class Verticle
{
/// <summary>
/// Имя
/// </summary>
public string Name { get; set; }
/// <summary>
/// Статус посещения узла
/// </summary>
public bool IsVisited { get; set; }
public Verticle(string name)
{
Name = name;
}
}

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

76
GrufCustom/Graph.cs Normal file

@ -0,0 +1,76 @@
using GraphCustomSearcher.Data;
namespace GraphCustomSearcher;
public class Graph
{
public List<Verticle> Verticls;
public List<Edge> Edges;
public string Path { get; set; }
public Verticle Target { get; set; }
public Graph()
{
Verticls = new List<Verticle>();
Edges = new List<Edge>();
}
/// <summary>
/// Загрузка узлов
/// </summary>
/// <param name="verticles">узлы</param>
public void AddVerticle(List<Verticle> verticles)
{
Verticls.AddRange(verticles);
}
/// <summary>
/// Загрузка рёбер
/// </summary>
/// <param name="edges">рёбра</param>
public void AddEdge(List<Edge> edges)
{
Edges.AddRange(edges);
}
public void RebuildEdge()
{
Path = string.Empty;
foreach (var edge in Edges)
{
edge.VerticleStop.IsVisited = false;
edge.VerticleStart.IsVisited = false;
}
}
/// <summary>
/// Перебор рёбер - поиск вершин в которые входит точка старта
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
public void SearchPath(string source, string target)
{
Console.WriteLine($"Начало: {source} Конец: {target}");
var sourceVerticle = new Verticle(source);
var targetVerticle = new Verticle(target);
foreach (var edge in Edges)
{
var state_1 = edge.VerticleStart.Name == sourceVerticle.Name && edge.VerticleStart.IsVisited == sourceVerticle.IsVisited;
var state_2 = !edge.VerticleStart.IsVisited;
var state_3 = !(!string.IsNullOrEmpty(Path) && Path.Contains(edge.VerticleStop.Name));
if (state_1 && state_2 && state_3)
{
Path += edge.VerticleStart.Name + " ";
Console.WriteLine($"Ребро {edge.VerticleStart.Name} направляется в {edge.VerticleStop.Name}");
edge.VerticleStart.IsVisited = true;
Target = edge.VerticleStop;
if (targetVerticle.Name == edge.VerticleStop.Name)
{
Path += edge.VerticleStop.Name;
return;
}
SearchPath(edge.VerticleStop.Name, targetVerticle.Name);
}
}
}
}

66
GrufCustom/Program.cs Normal file

@ -0,0 +1,66 @@
using GraphCustomSearcher.Data;
using GraphCustomSearcher;
/// <summary>
/// Ищет в направленном графе путь от точки до точки
/// учитывает наличие круговых двухсторонних связей
/// </summary>
public class Program
{
public static void Main()
{
var GraphX = new Graph();
var namesVerticles = new string[] { "Пенсильвания", "Париж", "Магеллан", "Аляска", "Аляска", "Оптимум"};
var wayEdges = new int[,] { { 0, 1 }, { 1, 0 }, { 1, 2 }, { 2, 1 }, { 2, 5 }, { 3, 1 }, { 3, 4 }, { 4, 3 } };
GraphX.AddVerticle(AddVerticles(namesVerticles));
GraphX.AddEdge(AddEdges(wayEdges, AddVerticles(namesVerticles)));
Console.WriteLine("Пенсильвания->Париж");
StartSeachPath(GraphX, "Пенсильвания", "Париж");
Console.WriteLine("Пенсильвания->Оптимум");
StartSeachPath(GraphX, "Пенсильвания", "Оптимум");
}
/// <summary>
/// Ищет путь от узла до узла
/// </summary>
/// <param name="graph">Граф</param>
/// <param name="start">Точка старта</param>
/// <param name="stop">Точка прибытия</param>
public static void StartSeachPath(Graph graph, string start, string stop)
{
Console.WriteLine();
graph.RebuildEdge();
graph.SearchPath(start, stop);
if (stop.Contains(graph.Target.Name))
Console.WriteLine($"--> PATH: {graph.Path}");
else Console.WriteLine("--> ERROR: Путь невозможен");
Console.WriteLine();
}
/// <summary>
/// Добавить узлы
/// </summary>
/// <param name="namesVerticles">список имён узлов</param>
/// <returns></returns>
public static List<Verticle> AddVerticles(string[] namesVerticles)
{
var VerticleList = new List<Verticle>();
foreach (var verticle in namesVerticles)
VerticleList.Add(new Verticle(verticle));
return VerticleList;
}
/// <summary>
/// Добавить рёбра (возможные пути между узлами)
/// </summary>
/// <param name="VerticleList"></param>
public static List<Edge> AddEdges(int[,] wayEdges, List<Verticle> VerticleList)
{
var EdgeList = new List<Edge>();
for(int ind = 0; ind < wayEdges.GetLength(0); ind++)
EdgeList.Add(new Edge(VerticleList[wayEdges[ind,0]], VerticleList[wayEdges[ind, 1]]));
return EdgeList;
}
}

11
README.md Normal file

@ -0,0 +1,11 @@
<p align="center">
<p align="center">
<a href="https://sites.google.com/view/dvurechensky" target="_blank"><img alt="Static Badge" src="https://img.shields.io/badge/Dvurechensky-N-blue"></a>
<img src="https://img.shields.io/badge/Csharp-VS2022-blue?logo=csharp&logoColor=FFFF00">
</p>
</p>
# Кастомный консольный Graph 🐠
- Ищет путь от точки до точки, в направленном графе
- Работает только в одном направлении сверху вниз
- Создавался для узкоспециализированной задачи и мало где может пригодиться 😵