2
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);

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

4

1 回答 1

2

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

广度和深度优先搜索 - 第 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 放在其他列上,表示没有通往这些城市的路径。

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

于 2010-03-08T04:36:59.907 回答