java实现图的广度优先遍历和深度优先遍历
/** * 图的广度优先遍历和深度优先遍历 */ @Data @AllArgsConstructor @NoArgsConstructor public class GraphBFS { private List<Node> nodes; private SetMultimap<String, Integer> edgeTable; public static void main(String[] args) { Set<String> nodes = Sets.newHashSet("A", "B", "C", "D", "E", "F", "G"); List<String> edges = Lists.newArrayList("A->B","A->C","A->D","B->E","E->F","C->G"); List<Node> nodeList = nodes.stream().map(node -> { Node node1 = new Node(); node1.setName(node); return node1; }).collect(Collectors.toList()); SetMultimap<String, Integer> multimap = HashMultimap.create(); edges.forEach(edge -> { String[] split = edge.split("->"); String start = split[0]; String end = split[1]; int index = getIndex(nodeList, end); multimap.put(start, index); }); System.out.println("===================bfs"); GraphBFS graph = new GraphBFS(nodeList, multimap); Node head = new Node("A", Color.WHITE); bfs(graph,head); System.out.println("===================dfs"); GraphBFS graphD = new GraphBFS(nodeList, multimap); dfs(graphD); } /** * 通过名字获取索引 * @param nodes * @param nodeName * @return */ public static int getIndex(List<Node> nodes,String nodeName) { for (int i = 0; i < nodes.size(); i++) { if(nodes.get(i).getName().equals(nodeName)){ return i; } } return -1; } /** * 广度优先遍历 * @param graph * @param headNode */ public static void bfs(GraphBFS graph,Node headNode) { Queue<Node> queue = new LinkedList<>(); List<Node> nodes = graph.getNodes(); SetMultimap<String, Integer> edgeTable = graph.getEdgeTable(); for (Node node : nodes) { node.setColor(Color.WHITE); } headNode.setColor(Color.RED); System.out.println(headNode); queue.add(headNode); while (!queue.isEmpty()) { Node node1 = queue.remove(); Set<Integer> integers = edgeTable.get(node1.name); for (Integer s : integers) { Node node = nodes.get(s); if (node.getColor() != Color.RED) { node.setColor(Color.RED); System.out.println(node); queue.add(node); } } } } /** * 深度优先遍历 * @param graph */ public static void dfs(GraphBFS graph) { List<Node> nodes = graph.getNodes(); for (Node node : nodes) { node.setColor(Color.WHITE); } for (Node node : nodes) { if (node.getColor().equals(Color.WHITE)) { doDFS(graph,node); } } } private static void doDFS(GraphBFS graph,Node node) { node.setColor(Color.RED); System.out.println(node); List<Node> nodes = graph.getNodes(); SetMultimap<String, Integer> edgeTable = graph.getEdgeTable(); Set<Integer> integers = edgeTable.get(node.getName()); for (Integer integer : integers) { Node node1 = nodes.get(integer); if (node1.getColor().equals(Color.WHITE)) { doDFS(graph,node1); } } } @Data @NoArgsConstructor @AllArgsConstructor static class Node{ private String name; private Color color; } enum Color{ WHITE,RED; } }