1. 程式人生 > 其它 >圖的建立、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集合中處理一個數後就不管其他數了
				}
		}
	}