반응형
다른 표현 방식
정점 클래스와 간선 클래스를 각각나누고 하는 그래프
노드클래스
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace study20
{
public class Node
{
public string key;
public LinkedList<Edge> edges;
public Node(string key)
{
this.key = key;
this.edges = new LinkedList<Edge>();
}
}
}
엣지 클래스
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace study20
{
public class Edge
{
public string from;
public string to;
public int weight;
public Edge(string from, string to, int weight)
{
this.from = from;
this.to = to;
this.weight = weight;
}
}
}
그래프클래스 (정점을 관리하는)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace study20
{
public class Graph
{
//정점 관리용 컬렉션 선언
public List<Node> nodes;
public Graph()
{
//컬렉션 인스턴스화
this.nodes = new List<Node>();
}
public void AddVetex(string key)
{
this.nodes.Add(new Node(key));
}
public void AddEdge(string from, string to, int weight = 1)
{
//정점리스트에서 from키를 갖는 요소(node)를 찾는다.
var fromVertex = this.nodes.Find(x => x.key == from);
fromVertex.edges.AddLast(new Edge(from, to, weight));
}
//출력
public void Print()
{
foreach (var vertex in this.nodes) {
var from = vertex.key;
foreach (var edge in vertex.edges) {
Console.WriteLine("{0} -- ({1}) -- {2}", from, edge.weight, edge.to);
}
}
}
}
}
----
app
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace study20
{
public class App
{
public App()
{
Graph g = new Graph();
g.AddVetex("서울");
g.AddVetex("강릉");
g.AddVetex("대전");
g.AddVetex("대구");
g.AddVetex("부산");
g.AddEdge("서울", "대전", 2);
g.AddEdge("서울", "강릉", 6);
g.AddEdge("대전", "대구", 3);
g.AddEdge("대전", "강릉", 5);
g.AddEdge("대구", "부산", 3);
g.Print();
}
}
}
반응형
'C# > 자료구조' 카테고리의 다른 글
0402_ 그래프 자료구조 이론 (0) | 2021.04.02 |
---|---|
0401_ 이진 탐색 트리 Search 메서드 (0) | 2021.04.01 |
0401_ 이진 탐색 트리 (Binary Search Tree : BST) // Add 메서드 (0) | 2021.04.01 |
0401 _ 반복방식 이진트리 중위순회 Iterative방식/while문 중복 없애기 (0) | 2021.04.01 |
0401 _ 반복방식 이진트리 중위순회 (0) | 2021.04.01 |