-
04/02 그래프 연습자료구조/수업내용 2021. 4. 2. 17:42
Program.cs
using System; namespace Study09 { class Program { static void Main(string[] args) { Console.WriteLine("Main"); new App(); } } }
App.cs
using System; namespace Study09 { public class App { //생성자 public App() { Console.WriteLine("App"); Graph g = new Graph(); g.AddVertex("서울"); g.AddVertex("대전"); g.AddVertex("대구"); g.AddVertex("부산"); g.AddVertex("강릉"); g.AddEdge("서울", "강릉", 10); g.AddEdge("서울", "대구", 7); g.AddEdge("서울", "대전", 6); g.AddEdge("대구", "부산", 3); g.AddEdge("대전", "부산", 7); g.AddEdge("강릉", "대구", 7); g.Print(); } } }
Node.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Study09 { //정점 클래스(Vertex) public class Node { //키 public string key; //생성자 public LinkedList<Edge> edges; public Node(string key) { this.key = key; this.edges = new LinkedList<Edge>(); } } }
Edge.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Study09 { public class Edge { //어디로부터 public string from; public string to; public int weight; public Edge(string from, string to, int weight = 1) { this.from = from; this.to = to; this.weight = weight; } } }
Graph.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Study09 { public class Graph { //정점 관리용 컬렉션 선언 public List<Node> nodes; public Graph() { this.nodes = new List<Node>(); } public void AddVertex(string key) { this.nodes.Add(new Node(key)); } public void AddEdge(string from, string to, int weight = 1) { var fromVertex = this.nodes.Find(x => x.key == from); var edge = new Edge(from, to, weight); fromVertex.edges.AddFirst(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); } } } } }
'자료구조 > 수업내용' 카테고리의 다른 글
04/02 수업내용 메모 (0) 2021.04.02 04/01 수업내용 메모 (0) 2021.04.01 04/01 연결리스트로 구현한 BinaryTree & Preorder Traversal 복습 (0) 2021.04.01 04/01 BinaryTree Preorder 순회 (Iterative) 복습 (0) 2021.04.01 03/31 수업내용 메모 (0) 2021.03.31