图的BFS,DFS
BFS: 利用栈可控制遍历正常结束,尤其对于有环图,是不可缺少的. 在每次出队时打印!
//给定图的一个节点,实现图的广度优先遍历
public static void bfs(Node<Integer> node){
if(node == null){
return;
}
Queue<Node<Integer>> queue = new LinkedList<>();
HashSet<Node<Integer>> set = new HashSet<>();
queue.add(node);
set.add(node);
while (!queue.isEmpty()){
Node<Integer> curr = queue.poll();
System.out.println(curr.val);
for (Node<Integer> next : curr.nexts) {
if(!set.contains(next)){
queue.add(next);
set.add(next);
}
}
}
}
DFS: 深度优先遍历,每次入栈时打印
//给定一个节点,实现图的深度优先遍历
private static void dfs(Node<Integer> node) {
if(node == null){
return;
}
Stack<Node<Integer>> stack = new Stack<>();
HashSet<Node<Integer>> set = new HashSet<>();
stack.add(node);
set.add(node);
System.out.println(node.val);
while (!stack.empty()){
Node<Integer> curr = stack.pop();
for (Node<Integer> next : curr.nexts) {
if(!set.contains(next)){
stack.push(curr);
stack.push(next);
set.add(next);
System.out.println(next.val);
break;
}
}
}
}
图结构的定义:
1.图的构成: 点集 边集
public class Graph<T> {
//点集
public HashMap<Integer,Node<T>> nodes;
//边集
public HashSet<Edge<T>> edges;
public Graph() {
this.nodes = new HashMap<>();
this.edges = new HashSet<>();
}
}
2.点集的构成: 节点
public class Node<T> {
public T val; //存储的数据
public int in; //入度
public int out; //出度
public ArrayList<Node<T>> nexts; //指向的节点
public ArrayList<Edge<T>> edges; //该节点含有的边
public Node(T val) {
this.val = val;
this.in = 0;
this.out = 0;
this.nexts = new ArrayList<>();
this.edges = new ArrayList<>();
}
}
3.边集的构成: 边
public class Edge<T> {
public Integer weight; //权重
public Node<T> from; //起点
public Node<T> to; //重点
public Edge(Integer weight, Node<T> from, Node<T> to) {
this.weight = weight;
this.from = from;
this.to = to;
}
}
4.给定一个矩阵生成对应的图
public class GraphGenerator {
public static void main(String[] args) {
int[][] matrix = {
{5, 1, 5},
{10, 4, 1},
{12, 6, 1},
{7, 6, 5},
{8, 8, 6},
{1, 5, 8},
{4, 8, 4}
};
createGraph(matrix);
}
/**
* @param matrix 生成图的数据 3 * N, 每组中分别代表 权重,from,to
* @return 生成的图
*/
public static Graph<Integer> createGraph(int[][] matrix) {
Graph<Integer> graph = new Graph<>();
for (int i = 0; i < matrix.length; i++) {
Integer weight = matrix[i][0];
Integer from = matrix[i][1];
Integer to = matrix[i][2];
if (!graph.nodes.containsKey(matrix[i][1])) {
graph.nodes.put(from, new Node<>(from));
}
if (!graph.nodes.containsKey(matrix[i][2])) {
graph.nodes.put(to, new Node<>(to));
}
Node<Integer> fromNode = graph.nodes.get(from);
Node<Integer> toNode = graph.nodes.get(to);
Edge<Integer> edge = new Edge<>(weight, fromNode, toNode);
fromNode.nexts.add(toNode);
fromNode.out++;
toNode.in++;
fromNode.edges.add(edge);
graph.edges.add(edge);
}
return graph;
}
}
左神算法学习