Guava Graph 深度/广度遍历

Guava Graph 深度/广度遍历:

import com.google.common.graph.*;


import java.util.*;
import java.util.stream.IntStream;

public class Main {

    static MutableValueGraph<String, Integer> graph = ValueGraphBuilder.directed().build();


    public static void main(String[] args) {

        IntStream.rangeClosed(1, 5).forEach(x -> {
            graph.addNode(String.valueOf(x));
        });


        graph.putEdgeValue("1", "4", 1);
        graph.putEdgeValue("1", "2", 1);
        graph.putEdgeValue("2", "4", 1);
        graph.putEdgeValue("2", "3", 1);
        graph.putEdgeValue("4", "5", 1);
        graph.putEdgeValue("4", "3", 1);
        graph.putEdgeValue("3", "5", 1);


        System.out.println("Graph:");
        System.out.println(graph.nodes());
        System.out.println(graph.edges());
        System.out.println("DFS:");
        dfs();
        System.out.println("\nBFS:");
        bfs();

    }

    static void bfs() {
        Set<String> visited = new HashSet<>();
        for (String node : graph.nodes()) {
            if (!visited.contains(node)) {
                bfs(visited, node);
            }
        }
    }

    static void bfs(Set<String> visited, String v) {
        Queue<String> queue = new LinkedList<>();
        queue.offer(v);
        while (!queue.isEmpty()) {
            String node = queue.poll();
            if(!visited.contains(node)){
                System.out.print(node + "->");
                visited.add(node);
            }
            for (String w : graph.successors(node)) {
                if (!visited.contains(w)) {
                    queue.offer(w);
                }
            }
        }

    }


    static void dfs() {
        Set<String> visited = new HashSet<>();
        for (String node : graph.nodes()) {
            if (!visited.contains(node)) {
                dfs(visited, node);
            }
        }

    }

    static void dfs(Set<String> visited, String v) {
        System.out.print(v + "->");
        visited.add(v);
        for (String w : graph.successors(v)) {
            if (!visited.contains(w)) {
                dfs(visited, w);
            }
        }
    }

}
个人资料
时海
等级:8
文章:272篇
访问:16.0w
排名: 2
上一篇: 图的深度遍历+广度遍历--java
下一篇:二分查找
标签: graph、面试题
隐藏