看起来带有整数列表作为值结构的字典可能会很有用:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, List<int>> graph = new Dictionary <int, List<int>>();
graph[1] = new List<int> {2, 3, 4};
graph[2] = new List<int> {1, 3, 4};
graph[3] = new List<int> {1, 2, 4};
graph[4] = new List<int> {1, 2, 3, 5};
graph[5] = new List<int> {4, 6};
graph[6] = new List<int> {5};
}
}
代码如下:
class Edge
{
public Node From;
public Node To;
}
class Node
{
public List<Edge> EdgesIn;
public List<Edge> EdgesOut;
}
class Graph
{
public List<Node> Nodes;
}
{
"graph": {
"mode":"NORMAL",
"vertices": [
{
"_id": "1",
"_type": "vertex"
},
{
"_id": "2",
"_type": "vertex"
},
{
"_id": "3",
"_type": "vertex"
}
],
"edges": [
{
"weight": 1,
"_id": "11",
"_type": "edge",
"_outV": "2",
"_inV": "1"
},
{
"weight": 0.5,
"_id": "12",
"_type": "edge",
"_outV": "3",
"_inV": "2"
}
]
}
}
C#中的邻接表工作示例。将边转换为C#中的邻接表
int[][] edges = new int[][]
{
new int[] { 0, 1 },
new int[] { 1, 2 },
new int[] { 2, 0 }
};
var graph = new Dictionary<int, List<int>>();
for (int i = 0; i < edges.Length; i++)
{
var pair = edges[i];
if (!graph.ContainsKey(pair[0])) graph.Add(pair[0], new List<int>());
if (!graph.ContainsKey(pair[1])) graph.Add(pair[1], new List<int>());
graph[pair[0]].Add(pair[1]);
graph[pair[1]].Add(pair[0]);
}