宽度优先遍历
1.利用队列实现
2.从原节点开始依次按照宽度进队列,然后弹出
3.每弹出一个节点,把该节点所以没有进过队列的邻节点放入队列
4.直到队列变为空
广度优先遍历
1.利用栈实现
2.从原节点开始把节点按照深度放入栈,然后弹出
3.每弹出一个节点,把该节点所有没有进过栈的节点放入栈中
4.直到栈变为空
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class GraphBFS{
public static class Node{
public int value;
public int in;//入度
public int out;//出度
public ArrayList<Node> nexts;//该点发出去的直接邻居点
public ArrayList<Edge> edges;//属于该点的边
public Node(int value){
this.value = value;
in = 0;
out = 0;
nexts = new ArrayList<>();
edges = new ArrayList<>();
}
}
public static class Edge{
public int weight;
public Node from;
public Node to;
public Edge(int weight,Node from,Node to){
this.weight = weight;
this.from = from;
this.to = to;
}
}
public static void bfs(Node node){
if(node == null){
return;
}
Queue<Node> queue = new LinkedList<>();
HashSet<Node> set = new HashSet<>();//为队列服务的,防止重复加入
queue.add(node);
set.add(node);//加入队列和set,set起注册作用
while(!queue.isEmpty()){
Node cur = queue.poll();
System.out.println(cur.value);//该步为处理,具体看题目情况
for(Node next : cur.nexts){//遍历该点的邻居点
if(!set.contains(next)){//如果没有在set中出现过,那么就加到set和队列中
set.add(next);
queue.add(next);
}
}
}
}
public static void dfs(Node node){
if(node == null){
return;
}
Stack<Node> stack = new Stack<>();
HashSet<Node> set = new HashSet<>();
stack.add(node);
set.add(node);
System.out.println(node.value);//深度优先遍历是进去的时候处理
while(!stack.isEmpty()){
Node cur = stack.pop();
for(Node next : cur.nexts){//遍历该点的邻居
if(!set.contains(next)){
stack.push(cur);//如果该点的邻居没有在set中,把他重新入栈
stack.push(next);
set.add(cur);
System.out.println(next.value);
break;//处理完他的一个邻居节点后直接break就行,其余邻居节点不用处理
}
}
}
}
}