Java中的邻接矩阵

Java中的邻接矩阵,第1张

Java中的邻接矩阵

首先,我是否要自己建立一个图(也许有节点和边类?),然后从中构造一个邻接矩阵?还是邻接矩阵本身就是图?

没有人真正阅读您的作业说明就无法肯定地回答该问题。但是,除非分配中特别提及Node和Edge类,否则我的猜测是您仅应使用邻接矩阵来表示图形。

然后,我对如何在程序中实现相邻矩阵感到困惑。节点被命名为“ ND5”和“ NR7”之类的东西,因此我将不得不设置并读取其边缘,[ND5][NR7]但是我不确定如何设置一个二维数组,其外部为字符串,内部为数字。

我完全可以理解您在这里的困惑。您实际要做的是 在节点名称和矩阵索引之间创建双射(一对一关系)。对于例如,如果你有Ñ在图中的节点,则需要一个n×n的矩阵(即new boolean[n][n]),并且每个节点将对应于一个单独的整数范围为0直到Ñ(不含n个)。

我不确定目前为止您班上已经讲过什么数据结构,但是最简单的方法可能是使用Map
它可以让您查找类似的名称”ND5”并获取整数(索引) 。

另一个不错的选择是使用数组。你可以把你所有的节点名称到一个数组,排序它Arrays.sort,然后一旦它的排序,你可以使用 发现,阵列中的特定节点名的索引。我认为该 解决方案实际上比使用a更好,因为它可以让您 双向进行查找。您曾经 用来进行名称到索引的查找,而您只是在数组中建立索引以执行索引到 名称的查找。
Arrays.binarySearch

Map

Arrays.binarySearch

给定该图,下面是一些示例代码,说明了如何执行此 *** 作:(警告!
未经测试)

import java.util.Arrays;// Add all your node names to an arrayString[] nameLookup = new String[4];nameLookup[0] = "A";nameLookup[1] = "B";nameLookup[2] = "C";nameLookup[3] = "D";// Our array is already properly sorted,// but yours might not be, so you should sort it.// (if it's not sorted then binarySearch won't work)Arrays.sort(nameLookup);// I'm assuming your edges are unweighted, so I use boolean.// If you have weighted edges you should use int or double.// true => connected, false => not connected// (entries in boolean arrays default to false)boolean[][] matrix = new boolean[4];for (int i=0; i<matrix.length; i++) matrix[i] = new boolean[4];// I don't want to call Arrays.binarySearch every time I want an index,// so I'm going to cache the indices here in some named variables.int nodeA = Arrays.binarySearch(nameLookup, "A");int nodeB = Arrays.binarySearch(nameLookup, "B");int nodeC = Arrays.binarySearch(nameLookup, "C");int nodeD = Arrays.binarySearch(nameLookup, "D");// I'm assuming your edges are undirected.// If the edges are directed then the entries needn't be semmetric.// A is connected to Bmatrix[nodeA][nodeB] = true;matrix[nodeB][nodeA] = true;// A is connected to Dmatrix[nodeA][nodeD] = true;matrix[nodeD][nodeA] = true;// B is connected to Dmatrix[nodeB][nodeD] = true;matrix[nodeD][nodeB] = true;// C is connected to Dmatrix[nodeC][nodeD] = true;matrix[nodeD][nodeC] = true;// Check if node X is connected to node Yint nodeX = Arrays.binarySearch(nameLookup, stringNameOfX);int nodeY = Arrays.binarySearch(nameLookup, stringNameOfY);if (matrix[nodeX][nodeY]) {  }// Print all of node Z's neighbors' namesint nodeZ = Arrays.binarySearch(nameLookup, stringNameOfZ);for (int i=0; i<matrix.length; i++) {  if (matrix[nodeZ][i]) {    System.out.println(nameLookup[nodeZ] + " is connected to " + nameLookup[i]);  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5561737.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存