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);
考虑到它是有向图,如何将它转换成邻接矩阵。
最佳答案
在这篇文章中,您可以找到一个邻接矩阵:
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的路径将我们引向锡比乌,蒂米什瓦拉和泽林德,因此在这种情况下,我们将代表这些城市的列的值设为1 ,即字母S,T和Z下方的列。这就是完成映射的方式。我们在其他列上设置了0值,以表明没有通往我们这些城市的路径。
给定您的图形,对其边缘进行迭代并创建邻接矩阵。