[英]Is this a proper implementation of a Graph for DFS, BFS
I'm learning about search algorithms BFS and DFS. 我正在学习搜索算法BFS和DFS。 I plan to implement both but before I do that, I need to implement my graph structure.
我计划实现两者,但在此之前,我需要实现我的图形结构。 Here's my idea:
这是我的主意:
A graph of connecting cities: Each city is represented by a Node. 连接城市的图形:每个城市都由一个节点表示。 Our graph will simply be an ArrayList of Nodes added as they're created, and each Node will have a list of it's neighbors, and a parent which will let us know where we came from (for path retrieval).
我们的图将只是创建时添加的Node的ArrayList,每个Node将具有其邻居的列表,以及一个父节点,该父节点将让我们知道我们来自哪里(用于路径检索)。 I haven't coded anything up yet, I wanted to get some feedback on my ideas before spending the time writing up something that won't work.
我还没有编写任何代码,所以我想在花时间编写不起作用的内容之前获得一些想法方面的反馈。 Here's some pseudocode-ish, code.
这是一些伪代码的代码。 One potential problem I can see is how we're going to deal with Nodes that we can get to from multiple places (multiple parents).
我看到的一个潜在问题是,我们将如何处理可以从多个地方(多个父节点)到达的节点。 If anyone has any suggestions on dealing with that, feel free to share.
如果有人对此有任何建议,请随时分享。
public class Node{
String name;
Node parent;
ArrayList<Node> neighbors;
public addNeighbor(Node n);
public setParent(Node n);
public getNeighbors()
...
}
public static void main(String[] args){
ArrayList<Node> graph = new ArrayList<Node>();
//build node
Node node = new Node(String name);
//add neighbors
node.addNeighbor(neighbor1);
node.addNeighbor(neighbor2);
//set parent
node.setParent(parent1);
//add to graph
graph.add(node);
path = dfs(graph, startNode, goalNode);
System.out.print(path);
}
Edit: I know I could look online and find implementations of this pretty easily, but I'd prefer to come up with my own solutions. 编辑:我知道我可以在网上查找并轻松找到此实现,但是我更愿意提出自己的解决方案。
Your implementation look good. 您的实现看起来不错。 It's the classic implentation of a graph structure (a node with a list of neighbors).
这是图结构(带有邻居列表的节点)的经典实现。 Some points:
一些要点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.