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