其他分享
首页 > 其他分享> > 图的建立、BFS、DFS

图的建立、BFS、DFS

作者:互联网

1、图的建立

public class Node {
	public int value;//自己数据项,节点值
	public int in;//点的入度,无向图的入度和出度一样
	public int out;//点的出度
	public ArrayList<Node> nexts;//从当前节点出发,由它发散出去的节点
	public ArrayList<Edge> edges;//属于当前节点的边,即out
	public Node(int val) {
		value = val;
		in = 0;
		out = 0;
		nexts = new ArrayList<>();
		edges = new ArrayList<>();
	}
}
public class Edge {
	public int weight;//边的权值
	public Node from;//有向边出发节点
	public Node to;
	public Edge(int wei,Node f,Node t) {
		weight = wei;
		from = f;
		to = t;
	}
}
public class GraphGenerator {
//接口函数
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Integer[][] matrix = {{5,0,1},{3,1,2},{7,0,2}};
		createGraph(matrix);
	}
	/*
	 * matrix解释:
	 * N * 3矩阵
	 * [ [5,0,1]  权重为1的边连接节点5到0
	 * 	 [3,1,2]  权重为2的边连接节点3到1
	 *   [7,0,2]  权重为2的边连接节点7到0
	 *   [form节点,to节点,权重],这三个数位置可变
	 * ]
	 */
	
	public static Graph createGraph(Integer[][] matrix) {
			Graph graph = new Graph();
			for(int i= 0;i < matrix.length;i++) {
				Integer form = matrix[i][0];
				Integer to = matrix[i][1];
				Integer weight = matrix[i][2];
				if(!graph.nodes.containsKey(form)) {//如果此时节点没有出现过
					graph.nodes.put(form,new Node(form));//把form点加入图里面
				}
				if(!graph.nodes.containsKey(to)) {
					graph.nodes.put(to, new Node(to));
				}
				
				Node fromNode = graph.nodes.get(form);//拿出form节点
				Node toNode = graph.nodes.get(to);
				Edge newEdge = new Edge(weight,fromNode,toNode);//新建边
				//修改一些数据
				fromNode.nexts.add(toNode);//从formNode节点出发指向toNode节点
				fromNode.out++;//出度++
				toNode.in++;//入度++
				fromNode.edges.add(newEdge);//新建的边属于fromNode节点
				graph.edges.add(newEdge);//最后把新建边放入图的边集合里
				
			}
			return graph;
	}

}

2、广度优先

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);
		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);
				}
			}
		}
	}

3、深度优先

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);//把cur重新压入栈
				stack.push(next);
				set.add(next);
				System.out.println(next.value);
				break;//把cur的nexts集合中处理一个数后就不管其他数了
				}
		}
	}

标签:Node,建立,graph,DFS,public,BFS,add,new,节点
来源: https://www.cnblogs.com/nofight/p/15984954.html