namespace TestProject;
/// <summary>
/// 그래프
/// </summary>
public class Graph
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Field
////////////////////////////////////////////////////////////////////////////////////////// Private
#region Field
/// <summary>
/// 버텍스 딕셔너리
/// </summary>
private Dictionary<string, Dictionary<string, int>> vertexDictionary = new Dictionary<string, Dictionary<string, int>>();
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////// Method
////////////////////////////////////////////////////////////////////////////////////////// Public
#region 에지 추가하기 - AddEdge(startNode, endNode, weight)
/// <summary>
/// 에지 추가하기
/// </summary>
/// <param name="startNode">시작 노드</param>
/// <param name="endNode">종료 노드</param>
/// <param name="weight">가중치</param>
public void AddEdge(string startNode, string endNode, int weight)
{
if(!this.vertexDictionary.ContainsKey(startNode))
{
this.vertexDictionary[startNode] = new Dictionary<string, int>();
}
this.vertexDictionary[startNode][endNode] = weight;
}
#endregion
#region 최단 경로 리스트 구하기 - GetShortestPathList(startNode, endNode)
/// <summary>
/// 최단 경로 리스트 구하기
/// </summary>
/// <param name="startNode">시작 노드</param>
/// <param name="endNode">종료 노드</param>
/// <returns>최단 경로 리스트</returns>
public List<string> GetShortestPathList(string startNode, string endNode)
{
Dictionary<string, int> distanceDictionary = new Dictionary<string, int>();
Dictionary<string, string> previousNodeDictionary = new Dictionary<string, string>();
List<string> nodeList = new List<string>();
List<string> pathList = null;
foreach(KeyValuePair<string, Dictionary<string, int>> keyValurPair in vertexDictionary)
{
if(keyValurPair.Key == startNode)
{
distanceDictionary[keyValurPair.Key] = 0;
}
else
{
distanceDictionary[keyValurPair.Key] = int.MaxValue;
}
nodeList.Add(keyValurPair.Key);
}
while(nodeList.Count != 0)
{
nodeList.Sort((x, y) => distanceDictionary[x].CompareTo(distanceDictionary[y]));
string smallestNode = nodeList[0];
nodeList.Remove(smallestNode);
if(smallestNode == endNode)
{
pathList = new List<string>();
while(previousNodeDictionary.ContainsKey(smallestNode))
{
pathList.Add(smallestNode);
smallestNode = previousNodeDictionary[smallestNode];
}
pathList.Add(startNode);
pathList.Reverse();
}
if(distanceDictionary[smallestNode] == int.MaxValue)
{
break;
}
if(vertexDictionary.ContainsKey(smallestNode))
{
foreach(KeyValuePair<string, int> neighbor in vertexDictionary[smallestNode])
{
if (!distanceDictionary.ContainsKey(neighbor.Key))
{
distanceDictionary[neighbor.Key] = int.MaxValue;
nodeList.Add(neighbor.Key);
}
var alt = distanceDictionary[smallestNode] + neighbor.Value;
if (alt < distanceDictionary[neighbor.Key])
{
distanceDictionary[neighbor.Key] = alt;
previousNodeDictionary[neighbor.Key] = smallestNode;
}
}
}
}
return pathList;
}
#endregion
}