邻接表中如何进行DFS和BFS?
创建邻接表:
HashMap <Interger,ArrayList<Integer>> adjList = new HashMap<Integer,ArrayList<Integer>>();
// adding element in Adjacency list (Undirected)
void AdjList(Integer a, Integer b){
adjList.putIfAbsent(a, new ArrayList<>());
adjList.get(a).add(b);
adjList.putIfAbsent(b, new ArrayList<>());
adjList.get(b).add(a);
}
如何在其中进行 DFS 和 BFS?
我尝试过这样的事情。如何循环通过?
void DFS(Integer i) {
//getting first element from adjlist
if (adjList.containsKey(i)) {
Integer ele1 = adjList.get(i).get(adjList.get(i).size() - 1);
if (adjList.containsKey(ele1)) {
Integer ele2 = adjList.get(ele1).get(adjList.get(ele1).size() - 1);
}
}
}
Creating an adjacency list:
HashMap <Interger,ArrayList<Integer>> adjList = new HashMap<Integer,ArrayList<Integer>>();
// adding element in Adjacency list (Undirected)
void AdjList(Integer a, Integer b){
adjList.putIfAbsent(a, new ArrayList<>());
adjList.get(a).add(b);
adjList.putIfAbsent(b, new ArrayList<>());
adjList.get(b).add(a);
}
How to do DFS and BFS in this?
I've tried something like this. how to loop through ?
void DFS(Integer i) {
//getting first element from adjlist
if (adjList.containsKey(i)) {
Integer ele1 = adjList.get(i).get(adjList.get(i).size() - 1);
if (adjList.containsKey(ele1)) {
Integer ele2 = adjList.get(ele1).get(adjList.get(ele1).size() - 1);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在正确创建邻接列表(但最好将此函数命名为
adjList
),但对于BFS
和DFS
,您需要每个节点都有一个已访问状态,并迭代一个节点的所有邻居节点,并对它们递归执行 BFS/DFS。上述代码的输出将是:
You are creating Adjacency List correctly(but it is better to name this function something like
adjList
), but for bothBFS
andDFS
, you need to have a visited status per node, and iterate over all nodes neighbors of a node and do the BFS/DFS recursively on them.The output of above code would be: