![](/user_photo/_userpic.png)
sd_6
.pdfПриложение А
using System;
namespace sd6
{
class program
{
static void Main(string[] args)
{
Console.Write("Введите кол-во узлов:");
int N = Convert.ToInt32(Console.ReadLine()); Console.Write("\nВведите кол-во ребер:"); int M = Convert.ToInt32(Console.ReadLine());
Console.Write("Введите город А: ");
int gorod = Convert.ToInt32(Console.ReadLine());
Console.Write("Введите город C: ");
int gorodC = Convert.ToInt32(Console.ReadLine()); Graph graph = new Graph(N, M);
graph.Print(); graph.D(gorod, gorodC); Console.ReadLine();
}
class Graph
{
int N, M; int[,] matrix;
public Graph(int N, int M)
{
this.N = N; this.M = M;
matrix = Matrix(this.N, this.M);
}
private static int[,] Matrix(int N, int M)
{
Random rand = new Random(); int[,] w = new int[N, N];
int count = 0;
for (int i = 0; i < N; i++)
{
for (int j = i; j < N; j++)
{
if (i == j)
{
w[i, j] = 0;
}
else
{
if (count < M)
{
w[i, j] = w[j, i] = rand.Next(0, 50); if (w[i, j] != 0) count++;
11
}
else
{
w[i, j] = w[j, i] = 0;
}
}
}
}
if (count < M)
{
for (int i = 0; i < N; i++)
{
for (int j = i; j < N; j++)
{
if (count < M && w[i, j] == 0 && i != j)
{
w[i, j] = w[j, i] = rand.Next(1, 50); count++;
}
}
}
}
return w;
}
public void Print()
{
Console.WriteLine("\nМатрица смежности\n"); for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
public void D(int g, int gC)
{
int[] pos = new int[N]; string[] way = new string[N]; bool[] node = new bool[N]; int min;
int indexm = 0;
for (int i = 0; i < N; i++)
{
pos[i] = 10000; node[i] = false; way[i] = "";
}
pos[g] = 0; pos[gC] = 0;
12
node[gC] = true;
for (int i = 0; i < N - 1; i++)
{
min = 10000;
for (int j = 0; j < N; j++)
{
if (!node[j] && pos[j] < min)
{
min = pos[j]; indexm = j;
}
}
node[indexm] = true; for (int j = 0; j < N; j++)
{
if (!node[j] && matrix[indexm, j] > 0 && pos[indexm] != 10000 && pos[indexm] + matrix[indexm, j] < pos[j])
{
pos[j] = pos[indexm] + matrix[indexm, j]; way[j] = way[j] + indexm + ", ";
}
}
}
for (int i = 0; i < N; i++)
{
way[i] = way[i] + i;
Console.WriteLine($"Город: " + i + " Вес: " + pos[i]); Console.WriteLine("Восстановленный путь: " + way[i]); Console.WriteLine();
}
Console.WriteLine();
}
}
}
}
13