图的深度优先遍历


import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Stack;

/**
* 图的深度优先遍历
*/
public class DepthFirst {

public static void df(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;
}
}
}
}

class Graph {

public HashMap<Integer, Node> nodes;

public HashSet<Edge> edges;

public Graph() {
nodes = new HashMap<>();
edges = new HashSet<>();
}

}

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;
nexts = new ArrayList<>();
edges = new ArrayList<>();
}

}

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

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
原文地址:https://www.cnblogs.com/laydown/p/13123818.html