1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package com.github.dexecutor.executor.graph;
19
20 import java.io.IOException;
21 import java.io.Writer;
22 import java.util.ArrayList;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Queue;
26 import java.util.Set;
27
28 import com.github.dexecutor.executor.graph.Graph.Node;
29
30
31
32
33
34
35
36
37
38 public class LevelOrderTraversar<T extends Comparable<T>, R> implements Traversar<T, R> {
39
40 private List<Graph.Node<T, R>> processed = new ArrayList<Graph.Node<T, R>>();
41
42 public void traverse(final Graph<T, R> graph, final Writer writer) {
43 List<List<List<Node<T, R>>>> levelOrderOfGraphs = traverseLevelOrder(graph);
44 int i = 0;
45 for (List<List<Node<T, R>>> levelOrderOfGraph : levelOrderOfGraphs) {
46 try {
47 writer.write("Path #" + (i++) + "\n");
48 printGraph(levelOrderOfGraph, writer);
49 writer.write("\n");
50 } catch (IOException e) {
51 e.printStackTrace();
52 }
53 }
54 }
55
56 private List<List<List<Node<T, R>>>> traverseLevelOrder(final Graph<T, R> graph) {
57 List<List<List<Node<T, R>>>> result = new ArrayList<List<List<Node<T, R>>>>();
58 Set<Node<T, R>> initialNodes = graph.getInitialNodes();
59 for (Node<T, R> iNode : initialNodes) {
60 List<List<Node<T, R>>> iresult = new ArrayList<List<Node<T, R>>>();
61 doTraverse(iresult, iNode);
62 result.add(iresult);
63 }
64 return result;
65 }
66
67 private void doTraverse(final List<List<Node<T, R>>> result, final Node<T, R> iNode) {
68 Queue<Node<T, R>> queue = new LinkedList<Node<T, R>>();
69 queue.offer(iNode);
70 while (!queue.isEmpty()) {
71 List<Node<T, R>> level = new ArrayList<Node<T, R>>();
72 int size = queue.size();
73 for (int i = 0; i < size; i++) {
74 Node<T, R> node = queue.poll();
75 if (!this.processed.contains(node)) {
76 if (!level.contains(node)) {
77 level.add(node);
78 }
79 this.processed.add(node);
80 for (Node<T, R> ogn : node.getOutGoingNodes()) {
81 if (ogn != null && !this.processed.contains(ogn)) {
82 queue.offer(ogn);
83 }
84 }
85 }
86
87 }
88 result.add(level);
89 }
90 }
91
92 private void printGraph(final List<List<Node<T, R>>> list, final Writer writer) {
93 for (List<Node<T, R>> nodes : list) {
94 try {
95 for (Node<T, R> node : nodes) {
96 writer.write(node + "" + node.getInComingNodes() + " ");
97 }
98 writer.write("\n");
99 } catch (IOException e) {
100 e.printStackTrace();
101 }
102 }
103 }
104 }