package com.lishilin;
import com.sun.istack.internal.NotNull;
import java.util.*;
public class Dfs {
public static class Node implements Comparable<Node> {
private String name;
private TreeSet<Node> set = new TreeSet<>();//有序的集合
public Node() {
}
public Node(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Node> getSet() {
return set;
}
public void setSet(TreeSet<Node> set) {
this.set = set;
}
@Override
public int compareTo(@NotNull Node o) {//排序规则
if(name.hashCode()>o.getName().hashCode())
return 1;
return 0;
}
}
public Node init() {//初始化一个图
Node nodeA = new Node("A");
Node nodeB = new Node("B");
Node nodeC = new Node("C");
Node nodeD = new Node("D");
Node nodeE = new Node("E");
Node nodeF = new Node("F");
Node nodeG = new Node("G");
Node nodeH = new Node("H");
nodeA.getSet().add(nodeB);
nodeA.getSet().add(nodeC);
nodeB.getSet().add(nodeD);
nodeB.getSet().add(nodeE);
nodeC.getSet().add(nodeF);
nodeC.getSet().add(nodeG);
nodeD.getSet().add(nodeH);
nodeE.getSet().add(nodeH);
return nodeA;
}
public void visite(Node node) {//访问每个节点
System.out.println(node.getName());
}
private Set<Node> open = new HashSet<>();
private Stack<Node> stack = new Stack<>();
public void dfs(Node begin) {
if(begin != null) {
stack.push(begin);//使用一个栈
open.add(begin);//标记已经访问过了
dfsLoop();
}
}
public void dfsLoop() {
Node peek = stack.pop();
visite(peek);
Set<Node> set = peek.getSet();//获取与当前节点直接关联的所有节点
for (Node node : set) {
if (!open.contains(node)) {//没有访问过
stack.push(node);
open.add(node);
dfsLoop();
}
}
}
public static void main(String[] args) {
Dfs dfs = new Dfs();
dfs.dfs(dfs.init());
}
}