码迷,mamicode.com
首页 > 其他好文 > 详细

图的深度优先遍历

时间:2020-06-14 10:50:30      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:from   system   ack   优先   list   contains   sem   stat   static   


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

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */

图的深度优先遍历

标签:from   system   ack   优先   list   contains   sem   stat   static   

原文地址:https://www.cnblogs.com/laydown/p/13123818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!