gpt4 book ai didi

java - 图邻接表的实现

转载 作者:行者123 更新时间:2023-12-02 08:19:18 25 4
gpt4 key购买 nike

我正在尝试实现非加权图的邻接列表和一些问题/疑虑。我意识到我需要一个链表来存储边和一个数组来存储顶点。目前我有一个(基本)Node 类和一个 Graph 类,它负责将边添加到特定顶点。然而,这并没有明确定义边的链接列表。我想做 DFS 和 BFS,想知道我应该怎么做?我是否需要更改已经包含这些方法的代码,或者现在是否需要更改。我们将不胜感激。

 // Inside the graph class

public boolean insertNode(NodeRecord n) {
int j;

if (isFull()) return false;
for (j=0; j<arraySize; j++)
if (node[j]==null)
break;
node[j] = new Node(n);
graphSize++;
return true;
}
public boolean insertEdge(int nodeID, EdgeRecord e) {
int j;

for (j=0; j<arraySize; j++)
if (nodeID==((NodeRecord) node[j].item).getID())
break;
if (j>=arraySize) return false;
node[j].next = new Node(e, node[j].next);
return true;
}

// inside the node class

class Node<E> {
E item;
Node<E> next;

Node(E e) {
item = e;
next = null;
}

Node(E e, Node<E> newNext) {
item = e;
next = newNext;
}

Node(Node<E> n) { // copy constructor
item = n.item;
next = n.next;
}

}

public static void depthFirst(){

for(int i=0;i<mygraph.arraySize;i++){
Node counter =mygraph.node[i];
while(counter!=null){
System.out.println(" " +counter.item);
counter= counter.next;
}

}
}

最佳答案

关于代码的一些注释:

  1. 您使用固定大小的数组来存储节点。切换到在添加新节点时自动增长的数组列表。

  2. 我是否正确理解,您可能只有一条边离开节点(next)?您还应该在此处使用列表。

  3. 只要您的图不是有向的,请注意从 A 到 B 的边也会从 B 到 A,因此您必须将其添加到节点 A 和节点 B 的边列表中。

关于java - 图邻接表的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com