1 |
|
---|
2 | using System;
|
---|
3 | using System.Collections.Generic;
|
---|
4 | namespace HeuristicLab.Problems.RoutePlanning.Graph {
|
---|
5 | public class Graph {
|
---|
6 | private IDictionary<long, Vertex> vertices;
|
---|
7 | private IDictionary<long, List<Edge<Vertex>>> adjacencyMap;
|
---|
8 | private IDictionary<long, List<Edge<Vertex>>> incidenceMap;
|
---|
9 |
|
---|
10 | public Graph() {
|
---|
11 | vertices = new Dictionary<long, Vertex>();
|
---|
12 | adjacencyMap = new Dictionary<long, List<Edge<Vertex>>>();
|
---|
13 | }
|
---|
14 |
|
---|
15 | public void AddVertex(Vertex vertex) {
|
---|
16 | vertices.Add(vertex.Id, vertex);
|
---|
17 | }
|
---|
18 |
|
---|
19 | public Vertex GetVertex(long id) {
|
---|
20 | Vertex vertex = null;
|
---|
21 | vertices.TryGetValue(id, out vertex);
|
---|
22 | return vertex;
|
---|
23 | }
|
---|
24 |
|
---|
25 | public void AddEdge(long startId, long endId) {
|
---|
26 | Vertex start = GetVertex(startId);
|
---|
27 | if (start == null) throw new ArgumentException(string.Format("Invalid vertex id {0}", startId), "startId");
|
---|
28 | Vertex end = GetVertex(startId);
|
---|
29 | if (end == null) throw new ArgumentException(string.Format("Invalid vertex id {0}", endId), "endId");
|
---|
30 |
|
---|
31 | Edge<Vertex> edge = new Edge<Vertex>(start, end);
|
---|
32 | //edge.Category = -1
|
---|
33 |
|
---|
34 | if (adjacencyMap[start.Id] == null) {
|
---|
35 | adjacencyMap[start.Id] = new List<Edge<Vertex>>();
|
---|
36 | }
|
---|
37 | adjacencyMap[start.Id].Add(edge);
|
---|
38 |
|
---|
39 | if (incidenceMap[end.Id] == null) {
|
---|
40 | incidenceMap[end.Id] = new List<Edge<Vertex>>();
|
---|
41 | }
|
---|
42 | incidenceMap[end.Id].Add(edge);
|
---|
43 | }
|
---|
44 |
|
---|
45 | public Edge<Vertex> GetEdge(long startId, long endId) {
|
---|
46 | List<Edge<Vertex>> edges = adjacencyMap[startId];
|
---|
47 | foreach (Edge<Vertex> edge in edges) {
|
---|
48 | if (edge.Target.Id == endId) {
|
---|
49 | return edge;
|
---|
50 | }
|
---|
51 | }
|
---|
52 | return null;
|
---|
53 | }
|
---|
54 |
|
---|
55 | public List<Edge<Vertex>> GetInEdges(long vertexId) {
|
---|
56 | return incidenceMap[vertexId];
|
---|
57 |
|
---|
58 | }
|
---|
59 |
|
---|
60 | public List<Edge<Vertex>> GetOutEdges(long vertexId) {
|
---|
61 | return adjacencyMap[vertexId];
|
---|
62 | }
|
---|
63 | }
|
---|
64 | }
|
---|