From afcdd2564f6e7db5040dad5072d7f210c0f2d0ce Mon Sep 17 00:00:00 2001 From: SnowBlackQueen Date: Sat, 12 Nov 2022 15:20:42 +0100 Subject: [PATCH 1/6] Primeros avances xD --- .../graphy/algorithms/AbstractAlgorithm.java | 2 +- .../algorithms/BridgeFinderAlgorithm.java | 272 +++++------ src/cu/edu/cujae/graphy/algorithms/Dial.java | 115 ++--- .../edu/cujae/graphy/algorithms/Kosaraju.java | 114 +++-- .../graphy/algorithms/MotherVertexFind.java | 150 +++--- src/cu/edu/cujae/graphy/core/Graph.java | 428 +++++++++--------- .../core/abstractions/AdjacencyListGraph.java | 240 +++++----- .../core/defaults/DefaultGraphBuilder.java | 128 +++--- .../graphy/core/trees/DefaultGeneralTree.java | 222 ++++----- 9 files changed, 849 insertions(+), 822 deletions(-) diff --git a/src/cu/edu/cujae/graphy/algorithms/AbstractAlgorithm.java b/src/cu/edu/cujae/graphy/algorithms/AbstractAlgorithm.java index 91c474a..f7bfd14 100644 --- a/src/cu/edu/cujae/graphy/algorithms/AbstractAlgorithm.java +++ b/src/cu/edu/cujae/graphy/algorithms/AbstractAlgorithm.java @@ -27,7 +27,7 @@ public abstract class AbstractAlgorithm implements Algorithm { - private T result; + T result; protected AbstractAlgorithm(T result) { diff --git a/src/cu/edu/cujae/graphy/algorithms/BridgeFinderAlgorithm.java b/src/cu/edu/cujae/graphy/algorithms/BridgeFinderAlgorithm.java index 78b016c..4d8b3f9 100644 --- a/src/cu/edu/cujae/graphy/algorithms/BridgeFinderAlgorithm.java +++ b/src/cu/edu/cujae/graphy/algorithms/BridgeFinderAlgorithm.java @@ -1,136 +1,136 @@ -/* - * Copyright (C) 2022 Javier Marrero. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package cu.edu.cujae.graphy.algorithms; - -import cu.edu.cujae.graphy.core.Edge; -import cu.edu.cujae.graphy.core.Graph; -import cu.edu.cujae.graphy.core.iterators.GraphIterator; -import cu.edu.cujae.graphy.utils.Pair; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; - -/** - * Given an undirected graph finds all the bridges. Like articulation points, bridges represent vulnerabilities in a - * connected network and are useful for designing reliable systems. A bridge is an edge which removing increases the - * number of disconnected components. - *

- * The time complexity of this algorithm is O(V + E) and O(BM) where M is the - * maximum branching of the DFS tree. - * - * @author Javier Marrero - */ -public class BridgeFinderAlgorithm extends AbstractAlgorithm>> -{ - - private static final int NIL = Integer.MIN_VALUE; - - private final Graph G; - private int time; - - public BridgeFinderAlgorithm(Graph graph) - { - super(new LinkedList<>()); - if (graph.isDirected()) - { - throw new IllegalArgumentException("the graph must be undirected"); - } - - // Initialize the parameters - this.G = graph; - this.time = 0; - } - - @Override - public Algorithm>> apply() - { - // Initialize the algorithm parameters - this.time = 0; - Set visited = new TreeSet<>(); - Map disc = new TreeMap<>(); - Map low = new TreeMap<>(); - Map parent = new TreeMap<>(); - - // Initialize the parent map - for (int i : G.getLabels()) - { - disc.put(i, 0); - low.put(i, 0); - parent.put(i, NIL); - } - - // Call the recursive vertex function to find all the bridges in the DFS tree - for (int i : G.getLabels()) - { - if (!visited.contains(i)) - { - bridgeUtil(i, visited, disc, low, parent); - } - } - - // This is mandated by the interface - return this; - } - - private void bridgeUtil(int u, Set visited, Map disc, Map low, - Map parent) - { - // Mark the current node as visited - visited.add(u); - - // Initialize discovery time and low value - low.put(u, ++time); - disc.put(u, low.get(u)); - - // Iterate for all the adjacent vertices - GraphIterator i = G.iterator(u); - for (Edge e : i.getAllAdjacentEdges()) - { - int v = (i.getEdgesDepartingSelf().contains(e)) ? e.getFinalNode().getLabel() : e.getStartNode().getLabel(); - - if (visited.contains(v) == false) - { - parent.put(v, u); - bridgeUtil(v, visited, disc, low, parent); - - // Check if the subtree rooted with v has a - // connection to one of the ancestors of u - low.put(u, Math.min(low.get(u), low.get(v))); - - // If the lowest vertex reachable from subtree - // under v is below u in DFS tree, then u-v is - // a bridge - if (low.get(v) > disc.get(u)) - { - getResult().add(new Pair<>(u, v)); - } - } - - // Update the low value of u for parent function calls - else if (v != parent.get(u)) - { - low.put(u, Math.min(low.get(u), disc.get(v))); - } - } - } - -} +/* + * Copyright (C) 2022 Javier Marrero. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.algorithms; + +import cu.edu.cujae.graphy.core.Edge; +import cu.edu.cujae.graphy.core.Graph; +import cu.edu.cujae.graphy.core.iterators.GraphIterator; +import cu.edu.cujae.graphy.utils.Pair; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +/** + * Given an undirected graph finds all the bridges. Like articulation points, bridges represent vulnerabilities in a + * connected network and are useful for designing reliable systems. A bridge is an edge which removing increases the + * number of disconnected components. + *

+ * The time complexity of this algorithm is O(V + E) and O(BM) where M is the + * maximum branching of the DFS tree. + * + * @author Javier Marrero + */ +public class BridgeFinderAlgorithm extends AbstractAlgorithm>> +{ + + private static final int NIL = Integer.MIN_VALUE; + + private final Graph G; + private int time; + + public BridgeFinderAlgorithm(Graph graph) + { + super(new LinkedList<>()); + if (graph.isDirected()) + { + throw new IllegalArgumentException("the graph must be undirected"); + } + + // Initialize the parameters + this.G = graph; + this.time = 0; + } + + @Override + public Algorithm>> apply() + { + // Initialize the algorithm parameters + this.time = 0; + Set visited = new TreeSet<>(); + Map disc = new TreeMap<>(); + Map low = new TreeMap<>(); + Map parent = new TreeMap<>(); + + // Initialize the parent map + for (int i : G.getLabels()) + { + disc.put(i, 0); + low.put(i, 0); + parent.put(i, NIL); + } + + // Call the recursive vertex function to find all the bridges in the DFS tree + for (int i : G.getLabels()) + { + if (!visited.contains(i)) + { + bridgeUtil(i, visited, disc, low, parent); + } + } + + // This is mandated by the interface + return this; + } + + private void bridgeUtil(int u, Set visited, Map disc, Map low, + Map parent) + { + // Mark the current node as visited + visited.add(u); + + // Initialize discovery time and low value + low.put(u, ++time); + disc.put(u, low.get(u)); + + // Iterate for all the adjacent vertices + GraphIterator i = G.iterator(u); + for (Edge e : i.getAllAdjacentEdges()) + { + int v = (i.getEdgesDepartingSelf().contains(e)) ? e.getFinalNode().getLabel() : e.getStartNode().getLabel(); + + if (visited.contains(v) == false) + { + parent.put(v, u); + bridgeUtil(v, visited, disc, low, parent); + + // Check if the subtree rooted with v has a + // connection to one of the ancestors of u + low.put(u, Math.min(low.get(u), low.get(v))); + + // If the lowest vertex reachable from subtree + // under v is below u in DFS tree, then u-v is + // a bridge + if (low.get(v) > disc.get(u)) + { + getResult().add(new Pair<>(u, v)); + } + } + + // Update the low value of u for parent function calls + else if (v != parent.get(u)) + { + low.put(u, Math.min(low.get(u), disc.get(v))); + } + } + } + +} diff --git a/src/cu/edu/cujae/graphy/algorithms/Dial.java b/src/cu/edu/cujae/graphy/algorithms/Dial.java index 5a9c348..5e36ae2 100644 --- a/src/cu/edu/cujae/graphy/algorithms/Dial.java +++ b/src/cu/edu/cujae/graphy/algorithms/Dial.java @@ -1,52 +1,63 @@ -/* - * Copyright (C) 2022 Ananda. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package cu.edu.cujae.graphy.algorithms; - -import cu.edu.cujae.graphy.core.Graph; -import cu.edu.cujae.graphy.utils.Pair; -import java.util.List; -import java.util.Map; - -/** - * El algoritmo de Dial, es decir, Dijkstra optimizado para pesos de rango pequeño, - * emplea una nueva estructura denominada cubo y posee una complejidad de tiempo - * O(E+WV), donde W es el peso máximo en cualquier borde del gráfico. - * La distancia máxima entre dos nodos puede tener un máximo de w(V-1). - * - * - * @author Ananda - * @param - */ -public class Dial extends AbstractAlgorithm>>> -{ - - private Graph graph; - - public Dial() - { - super(null); - } - - @Override - public Algorithm>>> apply() - { - throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody - } - -} +/* + * Copyright (C) 2022 Ananda. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.algorithms; + +import cu.edu.cujae.graphy.core.WeightedGraph; +import cu.edu.cujae.graphy.core.iterators.GraphIterator; +import cu.edu.cujae.graphy.utils.Pair; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * El algoritmo de Dial, es decir, Dijkstra optimizado para pesos de rango pequeño, + * emplea una nueva estructura denominada cubo y posee una complejidad de tiempo + * O(E+WV), donde W es el peso máximo en cualquier borde del gráfico. + * La distancia máxima entre dos nodos puede tener un máximo de w(V-1). + * + * + * @author Ananda + * @param + */ +public class Dial extends AbstractAlgorithm>>> +{ + private final WeightedGraph graph; + private final GraphIterator iter; + private final int vertex; + private final int label; + + public Dial(WeightedGraph graph, GraphIterator iter){ + super(new HashMap<>(graph.size())); + if (!graph.isWeighted()) + { + throw new IllegalArgumentException( + "Attempted to apply Dial algorithm to an unweighted graph."); + } + this.graph = graph; + this.iter = iter; + this.vertex = graph.size(); + this.label = iter.getLabel(); + } + + @Override + public Algorithm>>> apply(){ + + return this; + } +} diff --git a/src/cu/edu/cujae/graphy/algorithms/Kosaraju.java b/src/cu/edu/cujae/graphy/algorithms/Kosaraju.java index 1463bc3..4a2428b 100644 --- a/src/cu/edu/cujae/graphy/algorithms/Kosaraju.java +++ b/src/cu/edu/cujae/graphy/algorithms/Kosaraju.java @@ -1,49 +1,65 @@ -/* - * Copyright (C) 2022 Ananda. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package cu.edu.cujae.graphy.algorithms; - -import cu.edu.cujae.graphy.core.Graph; - -/** - * El algoritmo de Kosaraju está basado en DFS utilizado para encontrar componentes - * fuertemente conexos (SCC) en un grafo.Si uno es capaz de alcanzar un vértice v - * a partir del vértice u, entonces uno debería ser capaz de alcanzar el vértice u - * a partir de v y si se cumple, puede decirse que v y u están en un subgrafo - * fuertemente conectados. - * - * @author Ananda - * @param - */ -public class Kosaraju extends AbstractAlgorithm -{ - - private Graph graph; - - public Kosaraju() - { - super(null); - } - - @Override - public Algorithm apply() - { - throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody - } - -} +/* + * Copyright (C) 2022 Ananda. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.algorithms; + +import cu.edu.cujae.graphy.core.Graph; +import cu.edu.cujae.graphy.core.iterators.GraphIterator; +import java.util.ArrayDeque; + +/** + * El algoritmo de Kosaraju está basado en DFS utilizado para encontrar componentes + * fuertemente conexos (SCC) en un grafo.Si uno es capaz de alcanzar un vértice v + * a partir del vértice u, entonces uno debería ser capaz de alcanzar el vértice u + * a partir de v y si se cumple, puede decirse que v y u están en un subgrafo + * fuertemente conectados. + * + * @author Ananda + * @param + */ +public class Kosaraju extends AbstractAlgorithm +{ + private final Graph graph; + private final GraphIterator iter; + + public Kosaraju(GraphIterator iter, Graph graph) + { + super(Boolean.TRUE); + if (!graph.isDirected()) + { + throw new IllegalArgumentException( + "Attempted to apply Kosaraju algorithm to an undirected graph."); + } + this.graph = graph; + this.iter = iter; + } + + @Override + public Algorithm apply() + { + ArrayDeque stack = new ArrayDeque<>(); + GraphIterator dfs_iter = (GraphIterator) graph.depthFirstSearchIterator(iter.getLabel(), false); + while(dfs_iter.hasNext()){ + int label = dfs_iter.getLabel(); + stack.push(label); + dfs_iter.next(); + } + return this; + } + + } diff --git a/src/cu/edu/cujae/graphy/algorithms/MotherVertexFind.java b/src/cu/edu/cujae/graphy/algorithms/MotherVertexFind.java index 9c22493..de76175 100644 --- a/src/cu/edu/cujae/graphy/algorithms/MotherVertexFind.java +++ b/src/cu/edu/cujae/graphy/algorithms/MotherVertexFind.java @@ -1,75 +1,75 @@ -/* - * Copyright (C) 2022 Javier Marrero. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package cu.edu.cujae.graphy.algorithms; - -import cu.edu.cujae.graphy.core.Graph; -import cu.edu.cujae.graphy.core.iterators.GraphIterator; -import java.util.TreeSet; - -/** - * A mother vertex in a graph G = (V, E) is a vertex v such that all other vertices in G can be - * reached by a path from v. - * - * @author Javier Marrero - */ -public class MotherVertexFind extends AbstractAlgorithm -{ - - private final Graph G; - private final GraphIterator dfsIterator; - private final TreeSet visited; - - public MotherVertexFind(Graph graph) - { - super(null); - - // Graphs - this.G = graph; - this.dfsIterator = (GraphIterator) graph.depthFirstSearchIterator(true); - this.visited = new TreeSet<>(); - } - - @Override - public Algorithm apply() - { - // Store the last finished vertex - // (or mother vertex) - int v = -1; - - while (dfsIterator.hasNext()) - { - // Step to the next vertex - dfsIterator.next(); - - // Add this to the list of visited - if (!isVisited(dfsIterator.getLabel())) - { - - v = dfsIterator.getLabel(); - } - } - - return this; - } - - private boolean isVisited(int v) - { - return visited.contains(v); - } -} +/* + * Copyright (C) 2022 Javier Marrero. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.algorithms; + +import cu.edu.cujae.graphy.core.Graph; +import cu.edu.cujae.graphy.core.iterators.GraphIterator; +import java.util.TreeSet; + +/** + * A mother vertex in a graph G = (V, E) is a vertex v such that all other vertices in G can be + * reached by a path from v. + * + * @author Javier Marrero + */ +public class MotherVertexFind extends AbstractAlgorithm +{ + + private final Graph G; + private final GraphIterator dfsIterator; + private final TreeSet visited; + + public MotherVertexFind(Graph graph) + { + super(null); + + // Graphs + this.G = graph; + this.dfsIterator = (GraphIterator) graph.depthFirstSearchIterator(true); + this.visited = new TreeSet<>(); + } + + @Override + public Algorithm apply() + { + // Store the last finished vertex + // (or mother vertex) + int v = -1; + + while (dfsIterator.hasNext()) + { + // Step to the next vertex + dfsIterator.next(); + + // Add this to the list of visited + if (!isVisited(dfsIterator.getLabel())) + { + + v = dfsIterator.getLabel(); + } + } + + return this; + } + + private boolean isVisited(int v) + { + return visited.contains(v); + } +} diff --git a/src/cu/edu/cujae/graphy/core/Graph.java b/src/cu/edu/cujae/graphy/core/Graph.java index 3330fb0..35e328a 100644 --- a/src/cu/edu/cujae/graphy/core/Graph.java +++ b/src/cu/edu/cujae/graphy/core/Graph.java @@ -1,214 +1,214 @@ -/* - * Copyright (C) 2022 CUJAE. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package cu.edu.cujae.graphy.core; - -import cu.edu.cujae.graphy.core.iterators.GraphIterator; -import java.util.Collection; -import java.util.Iterator; - -/** - * The Graph interface represents a graph as an abstract - * data structure.The graph does not make a distinction with the data - * type it holds, it just presents an abstract model of a graph. - * - * @author Javier Marrero - * @param - */ -public interface Graph extends Iterable -{ - - /** - * Adds a new node to this graph with the specified index. - * - * @param label - * @param data - * - * @return a truth value representing wether insertion was successful. - */ - public boolean add(int label, T data); - - /** - * Adds a new node to this graph with a default allocated index. - * - * @param data - * - * @return a truth value representing wether insertion was successful. - */ - public boolean add(T data); - - /** - * Returns a BFS iterator to the selected node. - * - * @param node - * @param includeDisconnected - * - * @return a {@link Iterator} instance that is a BFS iterator. - */ - public Iterator breadthFirstSearchIterator(Node node, boolean includeDisconnected); - - /** - * The same as {@link Graph#breadthFirstSearchIterator(cu.edu.cujae.graphy.core.Node) } but with the integer label - * of the node. - * - * @param includeDisconnected - * - * @see Graph#breadthFirstSearchIterator(cu.edu.cujae.graphy.core.Node) - * @param v - * - * @return a {@link Iterator} instance. - */ - public Iterator breadthFirstSearchIterator(int v, boolean includeDisconnected); - - /** - * Returns a BFS iterator to a random node in the graph. - * - * @param includeDisconnected - * - * @return a {@link Iterator} - */ - public Iterator breadthFirstSearchIterator(boolean includeDisconnected); - - /** - * Connects two nodes in this graph. This method should return true if the connection was successful and false - * otherwise. The two input parameters are the labels of the nodes within the graph. - * - * @param u - * @param v - * - * @return - */ - public boolean connect(int u, int v); - - /** - * Connects two nodes within the graph. This version of the method uses the nodes directly. - * - * @param u - * @param v - * - * @return - */ - public boolean connect(Node u, Node v); - - /** - * Generates an iterator that performs a depth first search.Depth first traversal for a graph is similar to depth - * first traversal of a tree, the only catch being that, unlike trees, graphs may contain cycles (a node may be - * visited twice). This iterator avoids processing a node more than once. A graph may have more than one DFS - * traversal. - *

- * Depth-first search is an algorithm for traversing or searching a graph. The algorithm starts at the root node - * (some arbitrary node in this case, passed as a parameter) and explores as far as possible along each branch - * before backtracking. - *

- * The basic idea is to start from the root or any arbitrary node, and move to the next adjacent unmarked node. - * - * @param start - * @param includeDisconnected - * - * @return a new {@link Iterator} - */ - public Iterator depthFirstSearchIterator(Node start, boolean includeDisconnected); - - /** - * @param includeDisconnected - * - * @see Graph#depthFirstSearchIterator(cu.edu.cujae.graphy.core.Node) - * - * @param v the label of the node. - * - * @return - */ - public Iterator depthFirstSearchIterator(int v, boolean includeDisconnected); - - /** - * Generates an iterator that performs a depth first search, grabbing a random node as the root. - * - * @param includeDisconnected - * - * @see Graph#depthFirstSearchIterator(cu.edu.cujae.graphy.core.Node) - * @return a new {@link Iterator} - */ - public Iterator depthFirstSearchIterator(boolean includeDisconnected); - - /** - * Returns all the node labels of this graph. - * - * @return a {@link Collection} of integers representing node labels. - */ - public Collection getLabels(); - - /** - * Returns if the graph is a directed graph or not. - * - * @return true if the graph is a directed graph, false if otherwise. - */ - public boolean isDirected(); - - /** - * Returns if the graph is weighted or not. - * - * @return true if the graph is weighted, false if otherwise. - */ - public boolean isWeighted(); - - /** - * Returns true wether u and v are adjacent vertex in the graph. - * - * @param u - * @param v - * - * @return - */ - public boolean isVertexAdjacent(int u, int v); - - /** - * Returns a new {@link Iterator} for this graph. Order of iteration is not guaranteed, it may be insertion order or - * BSF or DSF. - * - * @return a new {@link Iterator} - */ - @Override - public Iterator iterator(); - - /** - * Returns a new {@link GraphIterator} for this node in the graph. Order of iteration is not guaranteed, commonly it - * will be a random access iterator, but this is implementation dependent. This method takes as a parameter the - * label of a particular node. - * - * @param v - * - * @return a new {@link GraphIterator} - */ - public GraphIterator iterator(int v); - - /** - * Registers an {@link EdgeFactory} instance to this class. This allows to vary the behavior of the graph as long as - * {@link Edge} creation refers. - * - * @param factory - */ - public void registerEdgeFactory(EdgeFactory factory); - - /** - * Returns the count of nodes in the graph. - * - * @return - */ - public int size(); - -} +/* + * Copyright (C) 2022 CUJAE. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.core; + +import cu.edu.cujae.graphy.core.iterators.GraphIterator; +import java.util.Collection; +import java.util.Iterator; + +/** + * The Graph interface represents a graph as an abstract + * data structure.The graph does not make a distinction with the data + * type it holds, it just presents an abstract model of a graph. + * + * @author Javier Marrero + * @param + */ +public interface Graph extends Iterable +{ + + /** + * Adds a new node to this graph with the specified index. + * + * @param label + * @param data + * + * @return a truth value representing wether insertion was successful. + */ + public boolean add(int label, T data); + + /** + * Adds a new node to this graph with a default allocated index. + * + * @param data + * + * @return a truth value representing wether insertion was successful. + */ + public boolean add(T data); + + /** + * Returns a BFS iterator to the selected node. + * + * @param node + * @param includeDisconnected + * + * @return a {@link Iterator} instance that is a BFS iterator. + */ + public Iterator breadthFirstSearchIterator(Node node, boolean includeDisconnected); + + /** + * The same as {@link Graph#breadthFirstSearchIterator(cu.edu.cujae.graphy.core.Node) } but with the integer label + * of the node. + * + * @param includeDisconnected + * + * @see Graph#breadthFirstSearchIterator(cu.edu.cujae.graphy.core.Node) + * @param v + * + * @return a {@link Iterator} instance. + */ + public Iterator breadthFirstSearchIterator(int v, boolean includeDisconnected); + + /** + * Returns a BFS iterator to a random node in the graph. + * + * @param includeDisconnected + * + * @return a {@link Iterator} + */ + public Iterator breadthFirstSearchIterator(boolean includeDisconnected); + + /** + * Connects two nodes in this graph. This method should return true if the connection was successful and false + * otherwise. The two input parameters are the labels of the nodes within the graph. + * + * @param u + * @param v + * + * @return + */ + public boolean connect(int u, int v); + + /** + * Connects two nodes within the graph. This version of the method uses the nodes directly. + * + * @param u + * @param v + * + * @return + */ + public boolean connect(Node u, Node v); + + /** + * Generates an iterator that performs a depth first search.Depth first traversal for a graph is similar to depth + * first traversal of a tree, the only catch being that, unlike trees, graphs may contain cycles (a node may be + * visited twice). This iterator avoids processing a node more than once. A graph may have more than one DFS + * traversal. + *

+ * Depth-first search is an algorithm for traversing or searching a graph. The algorithm starts at the root node + * (some arbitrary node in this case, passed as a parameter) and explores as far as possible along each branch + * before backtracking. + *

+ * The basic idea is to start from the root or any arbitrary node, and move to the next adjacent unmarked node. + * + * @param start + * @param includeDisconnected + * + * @return a new {@link Iterator} + */ + public Iterator depthFirstSearchIterator(Node start, boolean includeDisconnected); + + /** + * @param includeDisconnected + * + * @see Graph#depthFirstSearchIterator(cu.edu.cujae.graphy.core.Node) + * + * @param v the label of the node. + * + * @return + */ + public Iterator depthFirstSearchIterator(int v, boolean includeDisconnected); + + /** + * Generates an iterator that performs a depth first search, grabbing a random node as the root. + * + * @param includeDisconnected + * + * @see Graph#depthFirstSearchIterator(cu.edu.cujae.graphy.core.Node) + * @return a new {@link Iterator} + */ + public Iterator depthFirstSearchIterator(boolean includeDisconnected); + + /** + * Returns all the node labels of this graph. + * + * @return a {@link Collection} of integers representing node labels. + */ + public Collection getLabels(); + + /** + * Returns if the graph is a directed graph or not. + * + * @return true if the graph is a directed graph, false if otherwise. + */ + public boolean isDirected(); + + /** + * Returns if the graph is weighted or not. + * + * @return true if the graph is weighted, false if otherwise. + */ + public boolean isWeighted(); + + /** + * Returns true wether u and v are adjacent vertex in the graph. + * + * @param u + * @param v + * + * @return + */ + public boolean isVertexAdjacent(int u, int v); + + /** + * Returns a new {@link Iterator} for this graph. Order of iteration is not guaranteed, it may be insertion order or + * BSF or DSF. + * + * @return a new {@link Iterator} + */ + @Override + public Iterator iterator(); + + /** + * Returns a new {@link GraphIterator} for this node in the graph. Order of iteration is not guaranteed, commonly it + * will be a random access iterator, but this is implementation dependent. This method takes as a parameter the + * label of a particular node. + * + * @param v + * + * @return a new {@link GraphIterator} + */ + public GraphIterator iterator(int v); + + /** + * Registers an {@link EdgeFactory} instance to this class. This allows to vary the behavior of the graph as long as + * {@link Edge} creation refers. + * + * @param factory + */ + public void registerEdgeFactory(EdgeFactory factory); + + /** + * Returns the count of nodes in the graph. + * + * @return + */ + public int size(); + +} diff --git a/src/cu/edu/cujae/graphy/core/abstractions/AdjacencyListGraph.java b/src/cu/edu/cujae/graphy/core/abstractions/AdjacencyListGraph.java index 110766e..04f7d50 100644 --- a/src/cu/edu/cujae/graphy/core/abstractions/AdjacencyListGraph.java +++ b/src/cu/edu/cujae/graphy/core/abstractions/AdjacencyListGraph.java @@ -1,120 +1,120 @@ -/* - * Copyright (C) 2022 CUJAE. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package cu.edu.cujae.graphy.core.abstractions; - -import cu.edu.cujae.graphy.core.Graph; -import cu.edu.cujae.graphy.core.Node; -import cu.edu.cujae.graphy.core.defaults.DefaultNode; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - * An implementation of a graph using an adjacency list to keep track of the nodes. - * - * @author Javier Marrero - * @param - */ -public abstract class AdjacencyListGraph extends AbstractGraph implements Graph -{ - - private final Map> nodes; - - protected AdjacencyListGraph(boolean directed) - { - super(directed); - - nodes = new HashMap<>(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean add(int label, T data) - { - return nodes.putIfAbsent(label, new DefaultNode<>(label, data)) == null; - } - - /** - * {@inheritDoc } - */ - @Override - public Node findNodeByLabel(int label) - { - return nodes.get(label); - } - - /** - * {@inheritDoc } - */ - @Override - public Collection getLabels() - { - return nodes.keySet(); - } - - /** - * {@inheritDoc } - */ - @Override - protected Collection> getNodes() - { - return nodes.values(); - } - - /** - * {@inheritDoc } - */ - @Override - public boolean isVertexAdjacent(int u, int v) - { - return findNodeByLabel(u).isAdjacent(findNodeByLabel(v)); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() - { - StringBuilder builder = new StringBuilder("[\n"); - for (Iterator> it = nodes.values().iterator(); it.hasNext();) - { - Node node = it.next(); - builder.append(node.toString()); - if (it.hasNext()) - { - builder.append(",\n"); - } - } - return builder.append("\n]").toString(); - } - - /** - * {@inheritDoc } - */ - @Override - public int size() - { - return nodes.size(); - } - -} +/* + * Copyright (C) 2022 CUJAE. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.core.abstractions; + +import cu.edu.cujae.graphy.core.Graph; +import cu.edu.cujae.graphy.core.Node; +import cu.edu.cujae.graphy.core.defaults.DefaultNode; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * An implementation of a graph using an adjacency list to keep track of the nodes. + * + * @author Javier Marrero + * @param + */ +public abstract class AdjacencyListGraph extends AbstractGraph implements Graph +{ + + private final Map> nodes; + + protected AdjacencyListGraph(boolean directed) + { + super(directed); + + nodes = new HashMap<>(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean add(int label, T data) + { + return nodes.putIfAbsent(label, new DefaultNode<>(label, data)) == null; + } + + /** + * {@inheritDoc } + */ + @Override + public Node findNodeByLabel(int label) + { + return nodes.get(label); + } + + /** + * {@inheritDoc } + */ + @Override + public Collection getLabels() + { + return nodes.keySet(); + } + + /** + * {@inheritDoc } + */ + @Override + protected Collection> getNodes() + { + return nodes.values(); + } + + /** + * {@inheritDoc } + */ + @Override + public boolean isVertexAdjacent(int u, int v) + { + return findNodeByLabel(u).isAdjacent(findNodeByLabel(v)); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() + { + StringBuilder builder = new StringBuilder("[\n"); + for (Iterator> it = nodes.values().iterator(); it.hasNext();) + { + Node node = it.next(); + builder.append(node.toString()); + if (it.hasNext()) + { + builder.append(",\n"); + } + } + return builder.append("\n]").toString(); + } + + /** + * {@inheritDoc } + */ + @Override + public int size() + { + return nodes.size(); + } + +} diff --git a/src/cu/edu/cujae/graphy/core/defaults/DefaultGraphBuilder.java b/src/cu/edu/cujae/graphy/core/defaults/DefaultGraphBuilder.java index 8e52e53..3b67205 100644 --- a/src/cu/edu/cujae/graphy/core/defaults/DefaultGraphBuilder.java +++ b/src/cu/edu/cujae/graphy/core/defaults/DefaultGraphBuilder.java @@ -1,64 +1,64 @@ -/* - * Copyright (C) 2022 CUJAE. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package cu.edu.cujae.graphy.core.defaults; - -import cu.edu.cujae.graphy.core.Graph; -import cu.edu.cujae.graphy.core.GraphBuilder; - -/** - * This is a default implementation of the {@link GraphBuilder} interface. - * - * @author Javier Marrero - * @param - */ -public class DefaultGraphBuilder implements GraphBuilder -{ - - private DefaultSimpleGraph instance; - - public DefaultGraphBuilder() - { - this.instance = null; - } - - @Override - public GraphBuilder buildGraph() - { - // Create the instance - instance = new DefaultSimpleGraph<>(); - return this; - } - - @Override - public GraphBuilder directed(boolean directed) - { - instance.setDirected(directed); - instance.registerEdgeFactory((directed) ? (new DefaultDirectedEdgeFactory()) - : (new DefaultNotDirectedEdgeFactory())); - - return this; - } - - @Override - public Graph get() - { - return instance; - } - -} +/* + * Copyright (C) 2022 CUJAE. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.core.defaults; + +import cu.edu.cujae.graphy.core.Graph; +import cu.edu.cujae.graphy.core.GraphBuilder; + +/** + * This is a default implementation of the {@link GraphBuilder} interface. + * + * @author Javier Marrero + * @param + */ +public class DefaultGraphBuilder implements GraphBuilder +{ + + private DefaultSimpleGraph instance; + + public DefaultGraphBuilder() + { + this.instance = null; + } + + @Override + public GraphBuilder buildGraph() + { + // Create the instance + instance = new DefaultSimpleGraph<>(); + return this; + } + + @Override + public GraphBuilder directed(boolean directed) + { + instance.setDirected(directed); + instance.registerEdgeFactory((directed) ? (new DefaultDirectedEdgeFactory()) + : (new DefaultNotDirectedEdgeFactory())); + + return this; + } + + @Override + public Graph get() + { + return instance; + } + +} diff --git a/src/cu/edu/cujae/graphy/core/trees/DefaultGeneralTree.java b/src/cu/edu/cujae/graphy/core/trees/DefaultGeneralTree.java index 0c64c88..4307527 100644 --- a/src/cu/edu/cujae/graphy/core/trees/DefaultGeneralTree.java +++ b/src/cu/edu/cujae/graphy/core/trees/DefaultGeneralTree.java @@ -1,111 +1,111 @@ -/* - * Copyright (C) 2022 Javier Marrero. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package cu.edu.cujae.graphy.core.trees; - -import cu.edu.cujae.graphy.core.Node; -import cu.edu.cujae.graphy.core.TreeNode; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -/** - * Default implementation of the {@link Tree} interface. - * - * @author Javier Marrero - * @param - */ -public class DefaultGeneralTree extends AbstractTree -{ - - private final Map> nodes; - private TreeNode root; - - public DefaultGeneralTree() - { - this.nodes = new HashMap<>(); - this.root = null; - } - - @Override - public boolean add(int label, E data) - { - TreeNode newNode = new DefaultGeneralTreeNode<>(label, data); - if (root == null) - { - root = newNode; - } - return nodes.put(label, newNode) == null; - } - - @Override - public boolean add(TreeNode parent, E data) - { - throw new UnsupportedOperationException("not supported yet!"); - } - - @Override - public Node findNodeByLabel(int label) - { - return nodes.get(label); - } - - @Override - public Collection getLabels() - { - return nodes.keySet(); - } - - @Override - public TreeNode getRoot() - { - return root; - } - - @Override - public boolean isRoot(TreeNode node) - { - return root.equals(node); - } - - @Override - public boolean isVertexAdjacent(int u, int v) - { - throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody - } - - @Override - public boolean isWeighted() - { - ///TODO: Fixme - return false; - } - - @Override - public int size() - { - return nodes.size(); - } - - @Override - protected Collection> getNodes() - { - return nodes.values(); - } - -} +/* + * Copyright (C) 2022 Javier Marrero. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.core.trees; + +import cu.edu.cujae.graphy.core.Node; +import cu.edu.cujae.graphy.core.TreeNode; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +/** + * Default implementation of the {@link Tree} interface. + * + * @author Javier Marrero + * @param + */ +public class DefaultGeneralTree extends AbstractTree +{ + + private final Map> nodes; + private TreeNode root; + + public DefaultGeneralTree() + { + this.nodes = new HashMap<>(); + this.root = null; + } + + @Override + public boolean add(int label, E data) + { + TreeNode newNode = new DefaultGeneralTreeNode<>(label, data); + if (root == null) + { + root = newNode; + } + return nodes.put(label, newNode) == null; + } + + @Override + public boolean add(TreeNode parent, E data) + { + throw new UnsupportedOperationException("not supported yet!"); + } + + @Override + public Node findNodeByLabel(int label) + { + return nodes.get(label); + } + + @Override + public Collection getLabels() + { + return nodes.keySet(); + } + + @Override + public TreeNode getRoot() + { + return root; + } + + @Override + public boolean isRoot(TreeNode node) + { + return root.equals(node); + } + + @Override + public boolean isVertexAdjacent(int u, int v) + { + throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody + } + + @Override + public boolean isWeighted() + { + ///TODO: Fixme + return false; + } + + @Override + public int size() + { + return nodes.size(); + } + + @Override + protected Collection> getNodes() + { + return nodes.values(); + } + +} From c2409ee51dbf011cc8d70c3f8b069221c3362449 Mon Sep 17 00:00:00 2001 From: SnowBlackQueen Date: Sat, 12 Nov 2022 20:56:11 +0100 Subject: [PATCH 2/6] Primeros avances 1.1 --- .../graphy/algorithms/ColorableAlgorithm.java | 59 +++++++++++++++++++ .../{Dial.java => DialShortestPath.java} | 6 +- .../{Kosaraju.java => KosarajuAlgorithm.java} | 13 ++-- 3 files changed, 68 insertions(+), 10 deletions(-) create mode 100644 src/cu/edu/cujae/graphy/algorithms/ColorableAlgorithm.java rename src/cu/edu/cujae/graphy/algorithms/{Dial.java => DialShortestPath.java} (88%) rename src/cu/edu/cujae/graphy/algorithms/{Kosaraju.java => KosarajuAlgorithm.java} (83%) diff --git a/src/cu/edu/cujae/graphy/algorithms/ColorableAlgorithm.java b/src/cu/edu/cujae/graphy/algorithms/ColorableAlgorithm.java new file mode 100644 index 0000000..35c9200 --- /dev/null +++ b/src/cu/edu/cujae/graphy/algorithms/ColorableAlgorithm.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2022 Ananda. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.algorithms; + +import cu.edu.cujae.graphy.core.Graph; +import cu.edu.cujae.graphy.core.iterators.GraphIterator; + +/** + *El objetivo de este algoritmo es determinar si un grafo no dirigido puede ser + * coloreado con m colores, de forma tal que dos vértices adyacentes no posean + * igual coloratura. + * + * @author Ananda + * @param + */ +public class ColorableAlgorithm extends AbstractAlgorithm { + private final Graph graph; + private final int m; + private final String color; + private final GraphIterator iter; + + public ColorableAlgorithm(Graph graph, int m, String color, GraphIterator iter){ + super(Boolean.TRUE); + if(graph.isDirected()){ + throw new IllegalArgumentException( + "Attempted to apply Colorable algorithm to an directed graph."); + } + this.graph = graph; + this.m = m; + this.color = color; + this.iter = (GraphIterator) graph.depthFirstSearchIterator(false); + } + + @Override + public Algorithm apply(){ + while(iter.hasNext()){ + + } + + return this; + } + +} diff --git a/src/cu/edu/cujae/graphy/algorithms/Dial.java b/src/cu/edu/cujae/graphy/algorithms/DialShortestPath.java similarity index 88% rename from src/cu/edu/cujae/graphy/algorithms/Dial.java rename to src/cu/edu/cujae/graphy/algorithms/DialShortestPath.java index 5e36ae2..6f9d9ba 100644 --- a/src/cu/edu/cujae/graphy/algorithms/Dial.java +++ b/src/cu/edu/cujae/graphy/algorithms/DialShortestPath.java @@ -35,14 +35,14 @@ * @author Ananda * @param */ -public class Dial extends AbstractAlgorithm>>> +public class DialShortestPath extends AbstractAlgorithm>>> { private final WeightedGraph graph; private final GraphIterator iter; private final int vertex; private final int label; - public Dial(WeightedGraph graph, GraphIterator iter){ + public DialShortestPath(WeightedGraph graph, GraphIterator iter){ super(new HashMap<>(graph.size())); if (!graph.isWeighted()) { @@ -50,7 +50,7 @@ public Dial(WeightedGraph graph, GraphIterator iter){ "Attempted to apply Dial algorithm to an unweighted graph."); } this.graph = graph; - this.iter = iter; + this.iter = (GraphIterator) graph.depthFirstSearchIterator(false); this.vertex = graph.size(); this.label = iter.getLabel(); } diff --git a/src/cu/edu/cujae/graphy/algorithms/Kosaraju.java b/src/cu/edu/cujae/graphy/algorithms/KosarajuAlgorithm.java similarity index 83% rename from src/cu/edu/cujae/graphy/algorithms/Kosaraju.java rename to src/cu/edu/cujae/graphy/algorithms/KosarajuAlgorithm.java index 4a2428b..26252de 100644 --- a/src/cu/edu/cujae/graphy/algorithms/Kosaraju.java +++ b/src/cu/edu/cujae/graphy/algorithms/KosarajuAlgorithm.java @@ -32,12 +32,12 @@ * @author Ananda * @param */ -public class Kosaraju extends AbstractAlgorithm +public class KosarajuAlgorithm extends AbstractAlgorithm { private final Graph graph; private final GraphIterator iter; - public Kosaraju(GraphIterator iter, Graph graph) + public KosarajuAlgorithm(GraphIterator iter, Graph graph) { super(Boolean.TRUE); if (!graph.isDirected()) @@ -46,18 +46,17 @@ public Kosaraju(GraphIterator iter, Graph graph) "Attempted to apply Kosaraju algorithm to an undirected graph."); } this.graph = graph; - this.iter = iter; + this.iter = (GraphIterator) graph.depthFirstSearchIterator(iter.getLabel(), false); } @Override public Algorithm apply() { ArrayDeque stack = new ArrayDeque<>(); - GraphIterator dfs_iter = (GraphIterator) graph.depthFirstSearchIterator(iter.getLabel(), false); - while(dfs_iter.hasNext()){ - int label = dfs_iter.getLabel(); + while(iter.hasNext()){ + int label = iter.getLabel(); stack.push(label); - dfs_iter.next(); + iter.next(); } return this; } From 97c360057fc53bacea33fe3bf5ee10a63c889aec Mon Sep 17 00:00:00 2001 From: JoseCarlosGarcia Date: Sun, 13 Nov 2022 01:49:25 +0100 Subject: [PATCH 3/6] Merge cambios con el main --- lib/nblibraries.properties | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/lib/nblibraries.properties b/lib/nblibraries.properties index ae4a57c..81d722e 100644 --- a/lib/nblibraries.properties +++ b/lib/nblibraries.properties @@ -1,18 +1,18 @@ -libs.CopyLibs.classpath=\ - ${base}/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar -libs.CopyLibs.displayName=CopyLibs Task -libs.CopyLibs.prop-version=3.0 -libs.junit_5.classpath=\ - ${base}/junit_5/junit-jupiter-api-5.6.0.jar;\ - ${base}/junit_5/junit-jupiter-params-5.6.0.jar;\ - ${base}/junit_5/junit-jupiter-engine-5.6.0.jar -libs.junit_5.displayName=JUnit 5.6.0 -libs.junit_5.javadoc=\ - ${base}/junit_5/junit-jupiter-api-5.6.0-javadoc.jar;\ - ${base}/junit_5/junit-jupiter-params-5.6.0-javadoc.jar;\ - ${base}/junit_5/junit-jupiter-engine-5.6.0-javadoc.jar -libs.junit_5.prop-maven-dependencies=\n org.junit.jupiter:junit-jupiter-api:5.6.0:jar\n org.junit.jupiter:junit-jupiter-params:5.6.0:jar\n org.junit.jupiter:junit-jupiter-engine:5.6.0:jar\n -libs.junit_5.src=\ - ${base}/junit_5/junit-jupiter-api-5.6.0-sources.jar;\ - ${base}/junit_5/junit-jupiter-params-5.6.0-sources.jar;\ - ${base}/junit_5/junit-jupiter-engine-5.6.0-sources.jar +libs.CopyLibs.classpath=\ + ${base}/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar +libs.CopyLibs.displayName=CopyLibs Task +libs.CopyLibs.prop-version=3.0 +libs.junit_5.classpath=\ + ${base}/junit_5/junit-jupiter-api-5.6.0.jar;\ + ${base}/junit_5/junit-jupiter-params-5.6.0.jar;\ + ${base}/junit_5/junit-jupiter-engine-5.6.0.jar +libs.junit_5.displayName=JUnit 5.6.0 +libs.junit_5.javadoc=\ + ${base}/junit_5/junit-jupiter-api-5.6.0-javadoc.jar;\ + ${base}/junit_5/junit-jupiter-params-5.6.0-javadoc.jar;\ + ${base}/junit_5/junit-jupiter-engine-5.6.0-javadoc.jar +libs.junit_5.prop-maven-dependencies=\n org.junit.jupiter:junit-jupiter-api:5.6.0:jar\n org.junit.jupiter:junit-jupiter-params:5.6.0:jar\n org.junit.jupiter:junit-jupiter-engine:5.6.0:jar\n +libs.junit_5.src=\ + ${base}/junit_5/junit-jupiter-api-5.6.0-sources.jar;\ + ${base}/junit_5/junit-jupiter-params-5.6.0-sources.jar;\ + ${base}/junit_5/junit-jupiter-engine-5.6.0-sources.jar From 2575442de43b0246f096e1eb8d017a89248bf03a Mon Sep 17 00:00:00 2001 From: SnowBlackQueen Date: Sun, 13 Nov 2022 13:30:29 +0100 Subject: [PATCH 4/6] Rama development-SnowBlackQueen creada :) --- src/cu/edu/cujae/graphy/algorithms/DialShortestPath.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/cu/edu/cujae/graphy/algorithms/DialShortestPath.java b/src/cu/edu/cujae/graphy/algorithms/DialShortestPath.java index 6f9d9ba..fe6d40d 100644 --- a/src/cu/edu/cujae/graphy/algorithms/DialShortestPath.java +++ b/src/cu/edu/cujae/graphy/algorithms/DialShortestPath.java @@ -39,8 +39,6 @@ public class DialShortestPath extends AbstractAlgorithm graph; private final GraphIterator iter; - private final int vertex; - private final int label; public DialShortestPath(WeightedGraph graph, GraphIterator iter){ super(new HashMap<>(graph.size())); @@ -51,8 +49,6 @@ public DialShortestPath(WeightedGraph graph, GraphIterator iter){ } this.graph = graph; this.iter = (GraphIterator) graph.depthFirstSearchIterator(false); - this.vertex = graph.size(); - this.label = iter.getLabel(); } @Override From 659a40fe501e6d1cddd3e62a9549522c124ab8ee Mon Sep 17 00:00:00 2001 From: JoseCarlosGarcia Date: Sun, 13 Nov 2022 13:57:46 +0100 Subject: [PATCH 5/6] =?UTF-8?q?Algoritmo=20para=20obtener=20los=20v=C3=A9r?= =?UTF-8?q?tices=20aislados?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../graphy/algorithms/IsolatedVertices.java | 67 +++++++++++++ .../algorithms/IsolatedVerticesTest.java | 96 +++++++++++++++++++ 2 files changed, 163 insertions(+) create mode 100644 src/cu/edu/cujae/graphy/algorithms/IsolatedVertices.java create mode 100644 test/cu/edu/cujae/graphy/tests/algorithms/IsolatedVerticesTest.java diff --git a/src/cu/edu/cujae/graphy/algorithms/IsolatedVertices.java b/src/cu/edu/cujae/graphy/algorithms/IsolatedVertices.java new file mode 100644 index 0000000..853040a --- /dev/null +++ b/src/cu/edu/cujae/graphy/algorithms/IsolatedVertices.java @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2022 Jose. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.algorithms; + +import cu.edu.cujae.graphy.core.Graph; +import cu.edu.cujae.graphy.core.iterators.GraphIterator; +import java.util.LinkedList; +import java.util.Set; +import java.util.TreeSet; + +/** + * + * @author Jose + */ + +/*IsolatedVertices se realiza para poder obtener todos los vértices aislados en un grafo*/ + +public class IsolatedVertices extends AbstractAlgorithm> +{ + private final Graph graph; + public IsolatedVertices (Graph graph) + { + //En el caso de que no existan vértices aislados se retorna una lista vacía + super( new LinkedList()); + this.graph = graph; + } + + @Override + public Algorithm> apply() + { + //Lista para ir guardando los vertices aislados + LinkedList aislados = new LinkedList(); + //Lista para guardar los nodos visitados y no analizarlos de nuevo + Set visited = new TreeSet<>(); + + GraphIterator dfs = (GraphIterator) graph.depthFirstSearchIterator(true); + while(dfs.hasNext()) + { + dfs.next(); + //Si no ha sido visitado y no tiene aristas adyacentes + if(!visited.contains(dfs.getLabel()) && dfs.getAllAdjacentEdges().isEmpty()) + { + aislados.add(dfs.getLabel()); + visited.add(dfs.getLabel()); + } + } + setResult(aislados); + return this; + } + +} diff --git a/test/cu/edu/cujae/graphy/tests/algorithms/IsolatedVerticesTest.java b/test/cu/edu/cujae/graphy/tests/algorithms/IsolatedVerticesTest.java new file mode 100644 index 0000000..502f14a --- /dev/null +++ b/test/cu/edu/cujae/graphy/tests/algorithms/IsolatedVerticesTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2022 Jose. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.tests.algorithms; + +import cu.edu.cujae.graphy.algorithms.IsolatedVertices; +import cu.edu.cujae.graphy.core.Graph; +import cu.edu.cujae.graphy.core.defaults.DefaultGraphBuilder; +import java.util.Iterator; +import java.util.LinkedList; + +/** + * + * @author Jose + */ +public class IsolatedVerticesTest +{ + + public static void getIsolatedVertices (Graph graph) + { + LinkedList aux = (LinkedList) (new IsolatedVertices(graph)).apply().get(); + Iterator iter = aux.iterator(); + + if(!aux.isEmpty()) + { + while(iter.hasNext()) + { + Integer in = iter.next(); + System.out.println(in); + } + } + else + { + System.out.println("No existen vértices aislados en el grafo"); + } + } + + /** + * @param args the command line arguments + */ + public static void main(String[] args) + { + //Juego de datos para cuando existen vertices aislados + Graph graph = new DefaultGraphBuilder().buildGraph().directed(false).get(); + + for(int i = 0;i<10;i++) + { + graph.add(i, i); + } + + graph.connect(0, 1); + graph.connect(0, 2); + graph.connect(2, 3); + graph.connect(2, 4); + graph.connect(4, 5); + graph.connect(5, 6); + graph.connect(1, 9); + + getIsolatedVertices(graph); + + //Juego de datos para cuando no existen vertices aislados + Graph graph2 = new DefaultGraphBuilder().buildGraph().directed(false).get(); + + for(int i =0;i<10;i++) + { + graph2.add(i, i); + } + + graph2.connect(0, 1); + graph2.connect(0, 2); + graph2.connect(2, 3); + graph2.connect(2, 4); + graph2.connect(4, 5); + graph2.connect(5, 6); + graph2.connect(1, 9); + graph2.connect(7, 8); + + getIsolatedVertices(graph2); + } + +} From 3d089233ac02ed6e0a886d9021940f6da5d831a8 Mon Sep 17 00:00:00 2001 From: Javier Marrero Date: Sun, 13 Nov 2022 16:50:08 -0500 Subject: [PATCH 6/6] Added a few more utility functions to the nodes and iterators. --- src/cu/edu/cujae/graphy/core/Node.java | 8 + .../graphy/core/defaults/DefaultNode.java | 22 +- .../core/iterators/AbstractGraphIterator.java | 365 +++++++++--------- .../graphy/core/iterators/GraphIterator.java | 261 +++++++------ .../core/trees/DefaultGeneralTreeNode.java | 12 + 5 files changed, 358 insertions(+), 310 deletions(-) diff --git a/src/cu/edu/cujae/graphy/core/Node.java b/src/cu/edu/cujae/graphy/core/Node.java index 42a5fdd..9d23051 100644 --- a/src/cu/edu/cujae/graphy/core/Node.java +++ b/src/cu/edu/cujae/graphy/core/Node.java @@ -18,6 +18,7 @@ */ package cu.edu.cujae.graphy.core; +import java.util.Collection; import java.util.Set; /** @@ -78,6 +79,13 @@ public interface Node extends Cloneable */ public Edge getAdjacentEdge(Node v); + /** + * Returns a {@link Collection} containing all the adjacent vertices to this node. + * + * @return + */ + public Collection getAllAdjacentVertices(); + /** * Returns the set of edges connected to this node. If the node is isolated, it should return the empty set. This * set is an unmodifiable view of the {@link Node}'s internal container. diff --git a/src/cu/edu/cujae/graphy/core/defaults/DefaultNode.java b/src/cu/edu/cujae/graphy/core/defaults/DefaultNode.java index 67df83f..f84d12c 100644 --- a/src/cu/edu/cujae/graphy/core/defaults/DefaultNode.java +++ b/src/cu/edu/cujae/graphy/core/defaults/DefaultNode.java @@ -20,11 +20,7 @@ import cu.edu.cujae.graphy.core.Edge; import cu.edu.cujae.graphy.core.Node; -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.concurrent.CopyOnWriteArraySet; /** @@ -110,6 +106,22 @@ public Edge getAdjacentEdge(Node v) return getConnectionsFromVertex().get(v); } + @Override + public Collection getAllAdjacentVertices() + { + Collection nodes = new LinkedHashSet<>(getConnectionsFromVertex().size() + getConnectionsToVertex().size()); + for (Edge e : getEdgesArrivingSelf()) + { + nodes.add(e.getStartNode().getLabel()); + } + for (Edge e : getEdgesDepartingSelf()) + { + nodes.add(e.getFinalNode().getLabel()); + } + + return Collections.unmodifiableCollection(nodes); + } + /** * {@inheritDoc} */ diff --git a/src/cu/edu/cujae/graphy/core/iterators/AbstractGraphIterator.java b/src/cu/edu/cujae/graphy/core/iterators/AbstractGraphIterator.java index 58baa92..d5fcd1d 100644 --- a/src/cu/edu/cujae/graphy/core/iterators/AbstractGraphIterator.java +++ b/src/cu/edu/cujae/graphy/core/iterators/AbstractGraphIterator.java @@ -1,178 +1,187 @@ -/* - * Copyright (C) 2022 CUJAE. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package cu.edu.cujae.graphy.core.iterators; - -import cu.edu.cujae.graphy.core.Edge; -import cu.edu.cujae.graphy.core.Graph; -import cu.edu.cujae.graphy.core.Node; -import cu.edu.cujae.graphy.core.abstractions.AbstractGraph; -import java.util.Collection; -import java.util.Collections; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - -/** - * This class defines an abstract iterator class: an utility class that may be used to ease implementation of several - * iterator functionalities. - * - * @author Javier Marrero - * @param - */ -public abstract class AbstractGraphIterator implements GraphIterator -{ - - private final Graph graph; - private Node current; - - /** - * Construye un nuevo objeto iterador abstracto. - * - * @param graph - * @param current - */ - protected AbstractGraphIterator(Graph graph, Node current) - { - this.graph = graph; - this.current = current; - } - - /** - * {@inheritDoc} - */ - @Override - public T back() - { - throw new UnsupportedOperationException("This operation is not supported by this particular iterator."); - } - - /** - * {@inheritDoc} - */ - @Override - public Collection getAllAdjacentEdges() - { - Set candidates = new CopyOnWriteArraySet<>(getEdgesDepartingSelf()); - candidates.addAll(getEdgesArrivingSelf()); - - return Collections.unmodifiableCollection(candidates); - } - - /** - * {@inheritDoc} - */ - @Override - public Edge getAdjacentEdge(int v) - { - if (graph instanceof AbstractGraph) - { - return current.getAdjacentEdge(((AbstractGraph) graph).findNodeByLabel(v)); - } - else - { - for (Edge e : getEdgesDepartingSelf()) - { - if (e.getFinalNode().getLabel() == v) - { - return e; - } - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Collection getEdgesDepartingSelf() - { - return getCurrent().getEdgesDepartingSelf(); - } - - /** - * @return the current - */ - protected Node getCurrent() - { - return current; - } - - @Override - public Collection getEdgesArrivingSelf() - { - return getCurrent().getEdgesArrivingSelf(); - } - - /** - * {@inheritDoc } - */ - @Override - public int getLabel() - { - return current.getLabel(); - } - - /** - * {@inheritDoc } - */ - @Override - public boolean isAdjacent(Node node) - { - return current.isAdjacent(node); - } - - /** - * {@inheritDoc } - */ - @Override - public boolean isAdjacent(GraphIterator it) - { - return graph.isVertexAdjacent(current.getLabel(), it.getLabel()); - } - - /** - * {@inheritDoc } - *

- * This particular implementation is a stub and produces an exception whenever someone tries to random access a - * node. - */ - @Override - public T next(Node target) - { - throw new UnsupportedOperationException("This operation is not supported by this particular iterator"); - } - - /** - * {@inheritDoc } - */ - @Override - public T next(int u) - { - throw new UnsupportedOperationException("This operation is not supported by this particular iterator"); - } - - /** - * @param current the current to set - */ - protected void setCurrent(Node current) - { - this.current = current; - } - -} +/* + * Copyright (C) 2022 CUJAE. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.core.iterators; + +import cu.edu.cujae.graphy.core.Edge; +import cu.edu.cujae.graphy.core.Graph; +import cu.edu.cujae.graphy.core.Node; +import cu.edu.cujae.graphy.core.abstractions.AbstractGraph; +import java.util.Collection; +import java.util.Collections; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; + +/** + * This class defines an abstract iterator class: an utility class that may be used to ease implementation of several + * iterator functionalities. + * + * @author Javier Marrero + * @param + */ +public abstract class AbstractGraphIterator implements GraphIterator +{ + + private final Graph graph; + private Node current; + + /** + * Construye un nuevo objeto iterador abstracto. + * + * @param graph + * @param current + */ + protected AbstractGraphIterator(Graph graph, Node current) + { + this.graph = graph; + this.current = current; + } + + /** + * {@inheritDoc} + */ + @Override + public T back() + { + throw new UnsupportedOperationException("This operation is not supported by this particular iterator."); + } + + /** + * {@inheritDoc} + */ + @Override + public Collection getAllAdjacentEdges() + { + Set candidates = new CopyOnWriteArraySet<>(getEdgesDepartingSelf()); + candidates.addAll(getEdgesArrivingSelf()); + + return Collections.unmodifiableCollection(candidates); + } + + /** + * {@inheritDoc} + */ + @Override + public Collection getAllAdjacentVertices() + { + return current.getAllAdjacentVertices(); + } + + /** + * {@inheritDoc} + */ + @Override + public Edge getAdjacentEdge(int v) + { + if (graph instanceof AbstractGraph) + { + return current.getAdjacentEdge(((AbstractGraph) graph).findNodeByLabel(v)); + } + else + { + for (Edge e : getEdgesDepartingSelf()) + { + if (e.getFinalNode().getLabel() == v) + { + return e; + } + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Collection getEdgesDepartingSelf() + { + return getCurrent().getEdgesDepartingSelf(); + } + + /** + * @return the current + */ + protected Node getCurrent() + { + return current; + } + + @Override + public Collection getEdgesArrivingSelf() + { + return getCurrent().getEdgesArrivingSelf(); + } + + /** + * {@inheritDoc } + */ + @Override + public int getLabel() + { + return current.getLabel(); + } + + /** + * {@inheritDoc } + */ + @Override + public boolean isAdjacent(Node node) + { + return current.isAdjacent(node); + } + + /** + * {@inheritDoc } + */ + @Override + public boolean isAdjacent(GraphIterator it) + { + return graph.isVertexAdjacent(current.getLabel(), it.getLabel()); + } + + /** + * {@inheritDoc } + *

+ * This particular implementation is a stub and produces an exception whenever someone tries to random access a + * node. + */ + @Override + public T next(Node target) + { + throw new UnsupportedOperationException("This operation is not supported by this particular iterator"); + } + + /** + * {@inheritDoc } + */ + @Override + public T next(int u) + { + throw new UnsupportedOperationException("This operation is not supported by this particular iterator"); + } + + /** + * @param current the current to set + */ + protected void setCurrent(Node current) + { + this.current = current; + } + +} diff --git a/src/cu/edu/cujae/graphy/core/iterators/GraphIterator.java b/src/cu/edu/cujae/graphy/core/iterators/GraphIterator.java index a940533..254845b 100644 --- a/src/cu/edu/cujae/graphy/core/iterators/GraphIterator.java +++ b/src/cu/edu/cujae/graphy/core/iterators/GraphIterator.java @@ -1,127 +1,134 @@ -/* - * Copyright (C) 2022 CUJAE. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ -package cu.edu.cujae.graphy.core.iterators; - -import cu.edu.cujae.graphy.core.Edge; -import cu.edu.cujae.graphy.core.Node; -import java.util.Collection; -import java.util.Iterator; -import java.util.Set; - -/** - * A graph iterator is a special kind of iterator that allows random traversal of a graph. It extends the functionality - * found in {@link Iterator}, but does not replace it. One can still use a GraphIterator as a regular - * {@link Iterator}. - * - * @author Javier Marrero - * @param - */ -public interface GraphIterator extends Iterator -{ - - /** - * Returns to the last node left before stepping to this node. - * - * @return the data currently held by the iterator - */ - public T back(); - - /** - * Jumps to the specified node. - * - * @param target - * - * @return the data currently being held by the iterator - */ - public T back(Node target); - - /** - * Returns all the {@link Edge}s departing or arriving to this node. - * - * @return - */ - public Collection getAllAdjacentEdges(); - - /** - * This method should return the edges that depart from the pointed node. - * - * @return a collection of edges - */ - public Collection getEdgesDepartingSelf(); - - /** - * Returns the {@link Edge} connecting this iterator and the vertex with label v. - * - * @param v - * - * @return edge, or null if no edge connects this and v. - */ - public Edge getAdjacentEdge(int v); - - /** - * Returns the {@link Set} of edges that have the vertex pointed by this iterator as destination. - * - * @return a {@link Collection} of edges having this vertex as destination. - */ - public Collection getEdgesArrivingSelf(); - - /** - * Each node in a graph is somehow labeled. In this library, labels are integer indices that are unique to each - * node in the graph. This method should return the node's label of the node it is currently standing over. - * - * @return the label of the node that is the current iterating node - */ - public int getLabel(); - - /** - * Returns true if this iterator is adjacent to some specified {@link Node} - * - * @param node - * - * @return - */ - public boolean isAdjacent(Node node); - - /** - * Returns true if this iterator is adjacent to some node pointed by the specified {@link GraphIterator} - * - * @param it - * - * @return - */ - public boolean isAdjacent(GraphIterator it); - - /** - * Jumps to the specified {@link Node}. - * - * @param target - * - * @return - */ - public T next(Node target); - - /** - * Jumps to the node specified by this integer label. - * - * @param u - * - * @return - */ - public T next(int u); -} +/* + * Copyright (C) 2022 CUJAE. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ +package cu.edu.cujae.graphy.core.iterators; + +import cu.edu.cujae.graphy.core.Edge; +import cu.edu.cujae.graphy.core.Node; +import java.util.Collection; +import java.util.Iterator; +import java.util.Set; + +/** + * A graph iterator is a special kind of iterator that allows random traversal of a graph. It extends the functionality + * found in {@link Iterator}, but does not replace it. One can still use a GraphIterator as a regular + * {@link Iterator}. + * + * @author Javier Marrero + * @param + */ +public interface GraphIterator extends Iterator +{ + + /** + * Returns to the last node left before stepping to this node. + * + * @return the data currently held by the iterator + */ + public T back(); + + /** + * Jumps to the specified node. + * + * @param target + * + * @return the data currently being held by the iterator + */ + public T back(Node target); + + /** + * Returns all the {@link Edge}s departing or arriving to this node. + * + * @return + */ + public Collection getAllAdjacentEdges(); + + /** + * Returns a collection of all the adjacent vertices to this node. + * + * @return + */ + public Collection getAllAdjacentVertices(); + + /** + * This method should return the edges that depart from the pointed node. + * + * @return a collection of edges + */ + public Collection getEdgesDepartingSelf(); + + /** + * Returns the {@link Edge} connecting this iterator and the vertex with label v. + * + * @param v + * + * @return edge, or null if no edge connects this and v. + */ + public Edge getAdjacentEdge(int v); + + /** + * Returns the {@link Set} of edges that have the vertex pointed by this iterator as destination. + * + * @return a {@link Collection} of edges having this vertex as destination. + */ + public Collection getEdgesArrivingSelf(); + + /** + * Each node in a graph is somehow labeled. In this library, labels are integer indices that are unique to each + * node in the graph. This method should return the node's label of the node it is currently standing over. + * + * @return the label of the node that is the current iterating node + */ + public int getLabel(); + + /** + * Returns true if this iterator is adjacent to some specified {@link Node} + * + * @param node + * + * @return + */ + public boolean isAdjacent(Node node); + + /** + * Returns true if this iterator is adjacent to some node pointed by the specified {@link GraphIterator} + * + * @param it + * + * @return + */ + public boolean isAdjacent(GraphIterator it); + + /** + * Jumps to the specified {@link Node}. + * + * @param target + * + * @return + */ + public T next(Node target); + + /** + * Jumps to the node specified by this integer label. + * + * @param u + * + * @return + */ + public T next(int u); +} diff --git a/src/cu/edu/cujae/graphy/core/trees/DefaultGeneralTreeNode.java b/src/cu/edu/cujae/graphy/core/trees/DefaultGeneralTreeNode.java index 5e6a071..6c9a9ed 100644 --- a/src/cu/edu/cujae/graphy/core/trees/DefaultGeneralTreeNode.java +++ b/src/cu/edu/cujae/graphy/core/trees/DefaultGeneralTreeNode.java @@ -64,6 +64,18 @@ public void disconnect() throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody } + @Override + public Collection getAllAdjacentVertices() + { + Collection vertices = new LinkedList<>(); + getChildren(). + forEach(child -> + { + vertices.add(child.getLabel()); + }); + return Collections.unmodifiableCollection(vertices); + } + @Override @SuppressWarnings ("unchecked") public Collection> getChildren()