从JUNG图创建邻接矩阵

时间:2010-03-08 03:18:52

标签: java graph jung adjacency-matrix

Graph < Integer, Integer> g = new SparseMultigraph<Integer, Integer>();
    g.addVertex(1);g.addVertex(2);g.addVertex(3);
    g.addEdge(0,1,2 ,EdgeType.DIRECTED);g.addEdge(1,2,3 ,EdgeType.DIRECTED);g.addEdge(2,3,1 ,EdgeType.DIRECTED);g.addEdge(3,1,3 ,EdgeType.DIRECTED);

如何将此图转换为邻接矩阵,并考虑到它是有向图。

1 个答案:

答案 0 :(得分:2)

在这篇文章中你可以找到一个邻接矩阵:

Breadth and depth first search - part 3

如何实施?

// Adjacency matrix
int map[21][21] = {

/*   A B C D E F G H I L M N O P R S T U V Z */
  {0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0},
  {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1}, // Arad
  {2,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,0,1,0,0}, // Bucharest
  {3,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0}, // Craiova
  {4,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0}, // Dobreta
  {5,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0}, // Eforie
  {6,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, // Fagaras
  {7,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, // Girgiu
  {8,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0}, // Hirsova
  {9,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0}, // Iasi
  {0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0}, // Lugoj
  {1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0}, // Mehadia
  {2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0}, // Neamt
  {3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1}, // Oradea
  {4,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0}, // Pitesti
  {5,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0}, // Rimnicu Vilcea
  {6,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,0}, // Sibiu
  {7,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0}, // Timisoara
  {8,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0}, // Urziceni
  {9,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0}, // Vaslui
  {0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}  // Zerind
};

请注意,第一个注释行代表每个城市名称的首字母。使用邻接矩阵完成的映射是指这些字母,因此更容易理解。例如,获取引用Arad的邻接矩阵的第一个条目:我们有Arad有路径将我们引向Sibiu,Timisoara和Zerind,因此我们在表示这些城市的列上放置值1,在这种情况下,字母S,T和Z下面的列。这就是映射的完成方式。我们在其他列上放置了一个值0,表示没有路径将我们带到这些城市。

给出你的图形,迭代它的边并创建你的邻接矩阵。