总结了一下图的BFS和DFS,感觉有一些意义。贴出来吧
class Graph {
//创建图的类
public HashMap<Integer,Node> nodes;//点集
public HashSet<Edge>edges;//边集
public Graph(){
nodes=new HashMap<Integer,Node>();
edges=new HashSet<Edge>();
}
}
class Node{
public int value;//结点的值
public int in;//入度
public int out;//出度
public ArrayList<Node>nexts;//设置nexts为了便于访问其邻接点
public ArrayList<Edge>edges;
public Node(int value){
this.value=value;
in=0;
out=0;
nexts=new ArrayList<Node>();
edges=new ArrayList<Edge>();
}
}
class Edge{
public int weight;//边的权重
public Node from;//这里的from和to用于表达边连接两个节点的关系
public Node to;
public Edge(int weight,Node from,Node to){
this.weight=weight;
this.from=from;
this.to=to;
}
}
public class GraphGenerate{
//图的构造过程
public static Graph GraphGererator(int [][] matrix){
Graph graph=new Graph();
//图存放在一个N*3的矩阵中。
for (int i=0;i<matrix.length;i++){
int from=matrix[i][0];
int to=matrix[i][1];
int weight=matrix[i][2];
if (!graph.nodes.containsKey(from)){
graph.nodes.put(from,new Node(from));
}
if (graph.nodes.containsKey(to)){
graph.nodes.put(to,new Node(to));
}
Node fromNode=graph.nodes.get(from);
Node toNode =graph.nodes.get(to);
Edge newEdge=new Edge(weight,fromNode,toNode);
fromNode.out++;
toNode.in++;
fromNode.edges.add(newEdge);
toNode.edges.add(newEdge);
}
return graph;
}
}
class BFS{
public static void BFS(Node node) throws Exception {
if (node==null){
throw new Exception("给定结点为空");}
Queue<Node> queue=new LinkedList<>();//利用queue来控制访问图结构的一个顺序
HashSet<Node> set=new HashSet<>();//利用set来判断该结点是否被访问过。
queue.add(node);
set.add(node);
while(!queue.isEmpty()){
Node cur=queue.poll();
System.out.println(cur.value);
for (Node next:cur.nexts){
if (!set.contains(next)){
set.add(next);
queue.add(next);
}
}
}
}
}
class DFS{
public static void DFS(Node node) throws Exception {
if (node==null){
throw new Exception("给定结点为空");
}
Stack<Node>stack=new Stack<>();//利用栈的特性实现深度优先遍历
HashSet<Node>set=new HashSet<>();//set用来判断该结点是否被访问过。
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.add(cur);//这里要注意,cur此时还需要入栈,因为需要通过cur结点找到其相邻的未被访问过的结点
set.add(next);
stack.add(next);
System.out.println(next.value);
break;
}
}
}
}
}
创建图,并进行相应的DFS和BFS。其中读取的图是一个N*3的矩阵。第一列代表edge的起点,第二列代表edge的终点,第三列代表edge的weight。