Почему первый пункт повторяется дважды? - C#
Формулировка задачи:
Вот моя программа она находит все пути от первого пункта до второго пункта, но в результате мне выводятся где первый пункт повторяется дважды. Как исправить что бы он выводил вот так:
1 -> 2 = 10 1 -> 3 -> 2 = 10 1 -> 3 -> 4 -> 2 = 15 1 -> 4 -> 2 = 11 1 -> 4 -> 3 -> 2 = 12 Кратчайшее расстояние равно 10
Матрица для чтения вот
0;10;5;4 10;0;5;7 5;5;0;3 4;7;3;0Результат программы вот:
1 -> 2 = 10 1 -> 3 -> 1 -> 2 = 20 1 -> 3 -> 1 -> 4 -> 2 = 21 1 -> 3 -> 2 = 10 1 -> 3 -> 4 -> 1 -> 2 = 22 1 -> 3 -> 4 -> 2 = 15 1 -> 4 -> 1 -> 2 = 18 1 -> 4 -> 1 -> 3 -> 2 = 18 1 -> 4 -> 2 = 11 1 -> 4 -> 3 -> 1 -> 2 = 22 1 -> 4 -> 3 -> 2 = 12 Кратчайшее расстояние равно 10using System;
using System.IO;
using System.Collections.Generic;
namespace Grapher
{
class Graph
{
Dictionary<char, Dictionary<char, int>> vertices = new Dictionary<char, Dictionary<char, int>>();
public void add_vertex(char name, Dictionary<char, int> edges)
{
vertices[name] = edges;
}
public List<string> all_ways(char current, char end, string path, int weight)
{
List<string> pathes = new List<string>();
if (path.IndexOf(" " + current.ToString() + " ") != -1)
return pathes;
else
if (path == "")
path = current.ToString() + " = 0";
else
{
int index = path.IndexOf("=");
string temp = path.Substring(0, index);
string sum = path.Substring(index + 1);
weight += Convert.ToInt32(sum);
path = temp + "-> " + current.ToString() + " = " + weight.ToString();
}
if (current == end)
{
pathes.Add(path);
return pathes;
}
foreach (KeyValuePair<char, int> pair in vertices[current])
{
List<string> result = all_ways(pair.Key, end, path, pair.Value);
if (result.Count != 0)
pathes.AddRange(result);
}
return pathes;
}
public int shortest_path(char start, char finish)
{
var previous = new Dictionary<char, char>();
var distances = new Dictionary<char, int>();
var nodes = new List<char>();
List<char> path = null;
foreach (var vertex in vertices)
{
if (vertex.Key == start)
{
distances[vertex.Key] = 0;
}
else
{
distances[vertex.Key] = int.MaxValue;
}
nodes.Add(vertex.Key);
}
while (nodes.Count != 0)
{
nodes.Sort((x, y) => distances[x] - distances[y]);
var smallest = nodes[0];
nodes.Remove(smallest);
if (smallest == finish)
{
path = new List<char>();
while (previous.ContainsKey(smallest))
{
path.Add(smallest);
smallest = previous[smallest];
}
break;
}
if (distances[smallest] == int.MaxValue)
{
break;
}
foreach (var neighbor in vertices[smallest])
{
var alt = distances[smallest] + neighbor.Value;
if (alt < distances[neighbor.Key])
{
distances[neighbor.Key] = alt;
previous[neighbor.Key] = smallest;
}
}
}
if (path.Count > 0)
return distances[path[0]];
else
return 0;
}
}
class Program
{
static void Main(string[] args)
{
string[] data = File.ReadAllLines("data.txt");
int length = data[0].Split(';').Length, i;
Graph graph = new Graph();
for (i = 0; i < length; i++)
{
string[] str = data[i].Split(';');
var vertices = new Dictionary<char, int>();
for (int j = 0; j < length; j++)
if (Convert.ToInt32(str[j]) != 0)
vertices.Add(Char.Parse((j + 1).ToString()), Convert.ToInt32(str[j]));
graph.add_vertex(Char.Parse((i + 1).ToString()), vertices);
}
char start = '1'; // Номер начального пункта
char end = '2'; // Номер конечного пункта
var result = graph.all_ways(start, end, "", 0);
using (var sw = new StreamWriter("result.txt"))
{
foreach (var item in result)
sw.WriteLine(item);
sw.WriteLine("Кратчайшее расстояние равно " + graph.shortest_path(start, end));
}
Console.Write("Результат был сохранен в файле result.txt");
Console.ReadLine();
}
}
}Решение задачи: «Почему первый пункт повторяется дважды?»
textual
Листинг программы
if (path.IndexOf(current.ToString() + " ") != -1)