有苦有乐的算法 --- 图的深度优先遍历

题目

给定一个图,使用栈对其进行深度优先遍历

代码

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);
				stack.push(next);
				set.add(next);
				System.out.println(next.value);
				break;
			}
		}
	}
}
public 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<>();
	}
}
posted @ 2022-03-07 18:03  叕叕666  阅读(34)  评论(0)    收藏  举报