Advertisement
semkaegor4ik

graphStruct

Dec 14th, 2020
785
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 30.13 KB | None | 0 0
  1. package com.university.graphs;
  2.  
  3. import lombok.AccessLevel;
  4. import lombok.Data;
  5. import lombok.Getter;
  6.  
  7. import java.io.*;
  8. import java.util.*;
  9. import java.util.concurrent.atomic.AtomicBoolean;
  10. import java.util.concurrent.atomic.AtomicInteger;
  11. import java.util.stream.Collectors;
  12.  
  13. @Data
  14. public final class Graph {
  15.  
  16.     @Getter(value = AccessLevel.PRIVATE)
  17.     private final HashMap<Integer,Vertex> vertexHashMap;
  18.  
  19.     private TypeOfGraph typeOfGraph;
  20.  
  21.     private UIController controller;
  22.  
  23.     public Graph() {
  24.         vertexHashMap = new HashMap<>();
  25.     }
  26.  
  27.     public Graph(String filePath){
  28.         vertexHashMap = new HashMap<>();
  29.         initGraph(filePath);
  30.     }
  31.  
  32.     public Graph(Graph graph){
  33.         typeOfGraph = graph.getTypeOfGraph();
  34.         vertexHashMap = cloneGraph(graph.getVertexHashMap());
  35.     }
  36.  
  37.     public Graph(TypeOfGraph typeOfGraph) {
  38.         this.typeOfGraph = typeOfGraph;
  39.         vertexHashMap = new HashMap<>();
  40.     }
  41.  
  42.     public Graph(UIController controller) {
  43.         vertexHashMap = new HashMap<>();
  44.         this.controller = controller;
  45.     }
  46.  
  47.     public void show(){
  48.         vertexHashMap.forEach((id, vertex) -> System.out.println(vertex));
  49.     }
  50.  
  51.     public void addVertex(Integer id){
  52.         if(typeOfGraph == null){
  53.             throw new NullPointerException("type of graph didn't be init");
  54.         }
  55.         vertexHashMap.forEach((index, vertex) -> {
  56.             if(vertex.getId() == id){
  57.                 throw new IllegalArgumentException();
  58.             }
  59.         });
  60.         vertexHashMap.put(id, new Vertex(id));
  61.     }
  62.  
  63.     public void addArc(Integer from, Integer to){
  64.         if(TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)) {
  65.             vertexHashMap.get(from).addArc(to, 1);
  66.             vertexHashMap.get(to).addArc(from, 1);
  67.         }
  68.         else if(TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)){
  69.             vertexHashMap.get(from).addArc(to, 1);
  70.         }
  71.         else if(typeOfGraph != null){
  72.             throw new IllegalArgumentException("your graph has a weight, use addArcWithWeight()");
  73.         }
  74.         else{
  75.             throw new NullPointerException("type of graph didn't be init");
  76.         }
  77.     }
  78.  
  79.     public void addArcWithWeight(Integer from, Integer to, Integer weight){
  80.         if(TypeOfGraph.NOT_ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)) {
  81.             vertexHashMap.get(from).addArc(to, weight);
  82.             vertexHashMap.get(to).addArc(from, weight);
  83.         }
  84.         else if(TypeOfGraph.ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)){
  85.             vertexHashMap.get(from).addArc(to, weight);
  86.         }
  87.         else if(typeOfGraph != null){
  88.             throw new IllegalArgumentException("your graph hasn't a weight, use addArc()");
  89.         }
  90.         else{
  91.             throw new NullPointerException("type of graph didn't be init");
  92.         }
  93.     }
  94.  
  95.     public void deleteArc(Integer from, Integer to){
  96.         if(TypeOfGraph.NOT_ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph) ||
  97.                 TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)) {
  98.             vertexHashMap.get(from).deleteArc(to);
  99.             vertexHashMap.get(to).deleteArc(from);
  100.         }
  101.         else if(TypeOfGraph.ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)||
  102.                 TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)){
  103.             vertexHashMap.get(from).deleteArc(to);
  104.         }
  105.         else{
  106.             throw new NullPointerException("type of graph didn't be init");
  107.         }
  108.     }
  109.  
  110.     public void showVertexesDegrees(){
  111.         if(TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)||
  112.                 TypeOfGraph.NOT_ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)) {
  113.             vertexHashMap.forEach((id, vertex)->{
  114.                 int vertexDegree = vertex.getArcs().size();
  115.                 System.out.println("Vertex ID - " + id + " degree - " + vertexDegree);
  116.             });
  117.         }
  118.         else if(TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)||
  119.                 TypeOfGraph.ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)) {
  120.             vertexHashMap.forEach((id, vertex)->{
  121.                 int vertexDegree = vertex.getArcs().size();
  122.                 System.out.println("Vertex ID - " + id + " outcome " + vertexDegree);
  123.                 AtomicInteger inComeCount = new AtomicInteger();
  124.                 vertexHashMap.forEach((id1, vertex1)->{
  125.                     if(!id.equals(id1) &&
  126.                             vertex1.getArcs().containsKey(id)){
  127.                         inComeCount.getAndIncrement();
  128.                     }
  129.                 });
  130.                 System.out.println("Vertex ID - " + id + " income " + inComeCount);
  131.                 System.out.println();
  132.             });
  133.         }
  134.         else{
  135.             throw new NullPointerException("type of graph didn't be init");
  136.         }
  137.     }
  138.  
  139.     public void showHangingGraphVertices(){
  140.         if(TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)||
  141.                 TypeOfGraph.NOT_ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)) {
  142.             vertexHashMap.forEach((id, vertex) -> {
  143.                 if (vertex.getArcs().size() == 1) {
  144.                     System.out.println("Vertex ID - " + id);
  145.                 }
  146.             });
  147.         }
  148.         else if(TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)||
  149.                 TypeOfGraph.ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)) {
  150.             vertexHashMap.forEach((id, vertex)->{
  151.                 AtomicInteger vertexDegree = new AtomicInteger(vertex.getArcs().size());
  152.                 vertexHashMap.forEach((id1, vertex1)->{
  153.                     if(!id.equals(id1) &&
  154.                             vertex1.getArcs().containsKey(id)){
  155.                         vertexDegree.getAndIncrement();
  156.                     }
  157.                 });
  158.                 if(vertexDegree.get() == 1) {
  159.                     System.out.println("Vertex ID - " + id);
  160.                     System.out.println();
  161.                 }
  162.             });
  163.         }
  164.         else{
  165.             throw new NullPointerException("type of graph didn't be init");
  166.         }
  167.     }
  168.  
  169.     public Map<Integer, Integer> dijkstra(int from){
  170.  
  171.         if(TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)
  172.                 || TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph))
  173.             throw new IllegalArgumentException("your graph need to have weights");
  174.         else if(typeOfGraph == null)
  175.             throw new NullPointerException("type of graph didn't be init");
  176.  
  177.         vertexHashMap.forEach((id,vertex)->vertex.getArcs().forEach((index, weight)->{
  178.             if(weight < 0)
  179.                 throw new IllegalArgumentException("your graph need to have only positive weights");
  180.         }));
  181.  
  182.         Map<Integer, Integer> dijkstraResult = new HashMap<>();
  183.         vertexHashMap.forEach((id,vertex)->{
  184.             if(id!=from)
  185.                 dijkstraResult.put(id, Integer.MAX_VALUE);
  186.             else
  187.                 dijkstraResult.put(id, 0);
  188.         });
  189.  
  190.         Map<Integer, Boolean> used = new HashMap<>();
  191.         vertexHashMap.forEach((id,vertex)->used.put(id, false));
  192.  
  193.         AtomicInteger v = new AtomicInteger();
  194.  
  195.         for (int i = 0; i < vertexHashMap.size(); i++) {
  196.             v.set(-1);
  197.             vertexHashMap.forEach((id, vertex)->{
  198.                 if(!used.get(id)
  199.                         && (v.get() == -1 || dijkstraResult.get(id) < dijkstraResult.get(v.get())))
  200.                     v.set(id);
  201.             });
  202.  
  203.             if(dijkstraResult.get(v.get()) == Integer.MAX_VALUE)
  204.                 break;
  205.             used.put(v.get(),true);
  206.  
  207.             vertexHashMap.get(v.get()).getArcs().forEach((id,weight)->{
  208.                 if(dijkstraResult.get(id) > dijkstraResult.get(v.get()) + weight){
  209.                     dijkstraResult.put(id, dijkstraResult.get(v.get()) + weight);
  210.                 }
  211.             });
  212.         }
  213.         return dijkstraResult;
  214.     }
  215.  
  216.     public boolean hasAWay(Integer from, Integer to, List<Integer> vertexesList){
  217.         vertexesList.remove(from);
  218.         for (Integer id:
  219.                 vertexHashMap.get(from).getArcs().keySet()) {
  220.             if(id.equals(to)){
  221.                 return true;
  222.             }
  223.             else if(vertexesList.contains(id)){
  224.                 return hasAWay(id, to, vertexesList);
  225.             }
  226.         }
  227.         return false;
  228.     }
  229.  
  230.     public boolean hasAMinOstTree(){
  231.         List<Integer> finalVertexesList = getVertexesList();
  232.         List<Integer> vertexesListToDelete = getVertexesList();
  233.         for(Integer id : finalVertexesList){
  234.             List<Integer> vertexesList = getVertexesList();
  235.             if(!id.equals((Integer)1) && vertexesListToDelete.contains(id)){
  236.                 if(!hasAWay((Integer)1, id, vertexesList))
  237.                     return false;
  238.             }
  239.             vertexesListToDelete.removeIf(index -> !vertexesList.contains(index));
  240.         }
  241.         return true;
  242.     }
  243.  
  244.     public boolean isIsomorphic(Graph otherGraph){
  245.         AtomicBoolean isomorphism = new AtomicBoolean(true);
  246.         otherGraph.vertexHashMap.forEach((id, vertex)->{
  247.             if(!vertexHashMap.containsKey(id))
  248.                 isomorphism.set(false);
  249.         });
  250.         vertexHashMap.forEach((id, vertex)->{
  251.             if(!otherGraph.vertexHashMap.containsKey(id))
  252.                 isomorphism.set(false);
  253.         });
  254.  
  255.         otherGraph.vertexHashMap.forEach((otherId, otherVertex)-> vertexHashMap.forEach((id, vertex)->{
  256.             if(!vertex.isIsomorphic(otherVertex)&&
  257.                     (otherId.equals(id))){
  258.                 isomorphism.set(false);
  259.             }
  260.         }));
  261.         return isomorphism.get();
  262.     }
  263.  
  264.     public boolean hasACycle(){
  265.         for (Integer id:
  266.                 vertexHashMap.keySet()) {
  267.             List<Integer> vertexesList = new ArrayList<>();
  268.             vertexesList.add(id);
  269.             if(recourseForCycle(id, vertexesList))
  270.                 return true;
  271.         }
  272.        return false;
  273.     }
  274.  
  275.     public List<Arc> StronglyBondedComponents(){
  276.         if(TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)
  277.                 || TypeOfGraph.ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)) {
  278.             List<Arc> arcs = new ArrayList<>();
  279.             vertexHashMap.forEach((id, vertex) -> vertexHashMap.forEach((id1, vertex1) -> {
  280.                 if (vertex.getArcs().containsKey(id1) &&
  281.                         vertex1.getArcs().containsKey(id) &&
  282.                         !arcs.contains(new Arc(id1, id, vertex1.getArcs().get(vertex)))) {
  283.                     Arc newArc = new Arc(id, id1, vertex.getArcs().get(vertex1));
  284.                     arcs.add(newArc);
  285.                 }
  286.             }));
  287.             return arcs;
  288.         }
  289.         else if(TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)
  290.                 || TypeOfGraph.NOT_ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)){
  291.             throw new IllegalArgumentException("graph needs to be orienteering");
  292.         }
  293.         else{
  294.             throw new NullPointerException("type of graph didn't be init");
  295.         }
  296.     }
  297.  
  298.     public List<Integer> inComeList(Integer id){
  299.         List<Integer> inComeList = new ArrayList<>();
  300.         vertexHashMap.forEach((index, vertex)->{
  301.             if(vertex.getArcs().containsKey(id)){
  302.                 inComeList.add(index);
  303.             }
  304.         });
  305.         return inComeList;
  306.     }
  307.  
  308.     public List<Set<Integer>> getConnectivityComponents(){
  309.         if(typeOfGraph == null){
  310.             throw new NullPointerException("type of graph didn't be init");
  311.         }
  312.  
  313.         List<Set<Integer>> connectivityComponents =  new ArrayList<>();
  314.         List<Integer> vertexes = getVertexesList();
  315.  
  316.         vertexHashMap.forEach((id, vertex)->{
  317.             if(vertexes.contains(id)) {
  318.                 Set<Integer> component = new HashSet<>();
  319.                 recourseForConnectivityComponents(id, vertexes,component);
  320.                 connectivityComponents.add(component);
  321.             }
  322.         });
  323.         return connectivityComponents;
  324.     }
  325.  
  326.     public int numberOfConnectivityComponents(){
  327.         return getConnectivityComponents().size();
  328.     }
  329.  
  330.     public void deleteVertex(Integer vertId){
  331.         if(typeOfGraph == null){
  332.             throw new NullPointerException("type of graph didn't be init");
  333.         }
  334.         vertexHashMap.forEach((index, vertex) -> vertex.getArcs().remove(vertId));
  335.         vertexHashMap.remove(vertId);
  336.     }
  337.  
  338.     public void writeInFile(String fileName){
  339.         try(BufferedWriter fout = new BufferedWriter(new FileWriter(fileName))) {
  340.             if(TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)||
  341.                     TypeOfGraph.NOT_ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)){
  342.                 vertexHashMap.forEach((idFrom ,vertex)->{
  343.                     if(inComeList(idFrom).isEmpty() && vertex.getArcs().isEmpty()){
  344.                         try {
  345.                             fout.write(String.valueOf(idFrom));
  346.                             fout.newLine();
  347.                         } catch (IOException e) {
  348.                             e.printStackTrace();
  349.                         }
  350.                     }
  351.                     vertex.getArcs().forEach((idTo,weight)->{
  352.                         try {
  353.                             fout.write(idFrom + "-" + idTo);
  354.                             if(TypeOfGraph.NOT_ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)){
  355.                                 fout.write("(" + weight + ")");
  356.                             }
  357.                             fout.newLine();
  358.                         } catch (IOException e) {
  359.                             e.printStackTrace();
  360.                         }
  361.                     });
  362.                 });
  363.             }
  364.             else if(TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)||
  365.                     TypeOfGraph.ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)){
  366.                 vertexHashMap.forEach((idFrom ,vertex)->{
  367.                     if(inComeList(idFrom).isEmpty() && vertex.getArcs().isEmpty()){
  368.                         try {
  369.                             fout.write(String.valueOf(idFrom));
  370.                             fout.newLine();
  371.                         } catch (IOException e) {
  372.                             e.printStackTrace();
  373.                         }
  374.                     }
  375.                     vertex.getArcs().forEach((idTo,weight)->{
  376.                         try {
  377.                             fout.write(idFrom + ">" + idTo);
  378.                             if(TypeOfGraph.ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph)){
  379.                                 fout.write("(" + weight + ")");
  380.                             }
  381.                             fout.newLine();
  382.                         } catch (IOException e) {
  383.                             e.printStackTrace();
  384.                         }
  385.                     });
  386.                 });
  387.             }
  388.             else{
  389.                 throw new IllegalArgumentException();
  390.             }
  391.         }
  392.         catch (IOException ex){
  393.             ex.printStackTrace();
  394.         }
  395.     }
  396.  
  397.     public List<Integer> getVertexesList(){
  398.         List<Integer> vertexesList = new ArrayList<>();
  399.         vertexHashMap.forEach((id,vertex)->vertexesList.add(id));
  400.         return vertexesList;
  401.     }
  402.  
  403.     public Graph getMinOstTreeBorvki(){
  404.         if(!TypeOfGraph.NOT_ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph))
  405.             throw new IllegalArgumentException("your graph need to be not orienteering with weights");
  406.         Graph graph = new Graph(typeOfGraph);
  407.         getVertexesList().forEach(graph::addVertex);
  408.  
  409.         while (true){
  410.             List<Set<Integer>> components = graph.getConnectivityComponents();
  411.             if(components.size()==1)
  412.                 break;
  413.             components.forEach(set->{
  414.                 AtomicInteger min = new AtomicInteger(Integer.MAX_VALUE);
  415.                 AtomicInteger minIdFrom = new AtomicInteger(Integer.MIN_VALUE);
  416.                 AtomicInteger minIdTo = new AtomicInteger(Integer.MIN_VALUE);
  417.                 set.forEach(vertex-> vertexHashMap.get(vertex).getArcs().forEach((id, weight)->{
  418.                     if(!set.contains(id) && weight< min.get()){
  419.                         min.set(weight);
  420.                         minIdFrom.set(vertex);
  421.                         minIdTo.set(id);
  422.                     }
  423.                 }));
  424.                 if(!graph.vertexHashMap.get(minIdTo.get()).getArcs().containsKey(minIdFrom.get())){
  425.                     graph.addArcWithWeight(minIdFrom.get(), minIdTo.get(), min.get());
  426.                 }
  427.             });
  428.         }
  429.         return graph;
  430.     }
  431.  
  432.     public Graph getMinOstTreeKraskal(){
  433.         if(!TypeOfGraph.NOT_ORIENTEERING_WITH_WEIGHTS.equals(typeOfGraph))
  434.             throw new IllegalArgumentException("your graph need to be not orienteering with weights");
  435.         Graph graph = new Graph(typeOfGraph);
  436.         getVertexesList().forEach(graph::addVertex);
  437.  
  438.  
  439.  
  440.  
  441.  
  442.         return graph;
  443.     }
  444.  
  445.  
  446.     public Map<Integer,Integer> fordBellman(Integer vertexId){
  447.         if(TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)
  448.                 || TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph))
  449.             throw new IllegalArgumentException("your graph need to have weights");
  450.         else if(typeOfGraph == null)
  451.             throw new NullPointerException("type of graph didn't be init");
  452.  
  453.         Set<Arc> arcs = new HashSet();
  454.         Map<Integer,Integer> result = new HashMap<>();
  455.         vertexHashMap.forEach((id, vertex)->{
  456.             if(!id.equals(vertexId))
  457.                 result.put(id, Integer.MAX_VALUE);
  458.             else
  459.                 result.put(id, 0);
  460.             vertex.getArcs().forEach((index, weight)->arcs.add(new Arc(id, index, weight)));
  461.         });
  462.         result.forEach((id, distance) -> arcs.forEach(arc ->{
  463.             if(result.get(arc.getFirstId()) < Integer.MAX_VALUE)
  464.                 result.replace(arc.getSecondId(), Math.min(result.get(arc.getSecondId()), result.get(arc.getFirstId()) + arc.getWeight()));
  465.         }));
  466.         return result;
  467.     }
  468.  
  469.     public Set<Map<Integer, Integer>> allMinDistance(){
  470.         Set<Map<Integer, Integer>> allMinDistance = new HashSet<>();
  471.         vertexHashMap.forEach((id, vertex)->allMinDistance.add(fordBellman(id)));
  472.         return allMinDistance;
  473.     }
  474.  
  475.     public Map<Integer, Integer> allMinDistanceToVertex(Integer vertexId){
  476.         Map<Integer, Integer> allMinDistanceToVertex = new HashMap<>();
  477.         vertexHashMap.forEach((id, vertex)->{
  478.             allMinDistanceToVertex.put(id,fordBellman(id).get(vertexId));
  479.         });
  480.         return allMinDistanceToVertex;
  481.     }
  482.  
  483.     public List<Arc> getAllArcs(){
  484.         List<Arc> allArcs = new ArrayList<>();
  485.         vertexHashMap.forEach((id, vertex)->vertex.getArcs().forEach((index, weight)->allArcs.add(new Arc(id, index, weight))));
  486.         return allArcs;
  487.     }
  488.  
  489.     public int getMaxFlow(Integer source, Integer stock){
  490.         if(TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)
  491.                 ||TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph))
  492.             throw new IllegalArgumentException("your graph need to have weights");
  493.         else if(inComeList(stock).size()==0
  494.                 ||vertexHashMap.get(source).getArcs().size()==0){
  495.             return -1;
  496.         }
  497.         Set<List<Arc>> allWays = getAllWays(source, stock);
  498.         List<ArcWithFlow> allArcsWithFlow= new ArrayList<>();
  499.         getAllArcs().forEach(arc->allArcsWithFlow.add(new ArcWithFlow(arc.getFirstId(), arc.getSecondId(), arc.getWeight(), 0)));
  500.  
  501.         allWays.forEach(way->{
  502.             AtomicInteger min = new AtomicInteger(Integer.MAX_VALUE);
  503.             way.forEach(arc-> allArcsWithFlow.forEach(arcWithFlow -> {
  504.                 if (arcWithFlow.getWeight() < min.get()
  505.                         &&arc.equalsArcWithFlow(arcWithFlow)) {
  506.                     min.set(arcWithFlow.getWeight());
  507.                 }
  508.             }));
  509.             allArcsWithFlow.forEach(arcWithFlow->way.forEach(arc->{
  510.                 if(arc.equalsArcWithFlow(arcWithFlow)){
  511.                     arcWithFlow.setFlow(arcWithFlow.getFlow() + min.get());
  512.                     arcWithFlow.setWeight(arcWithFlow.getWeight() - min.get());
  513.                 }
  514.             }));
  515.         });
  516.  
  517.         return allArcsWithFlow.stream().filter(arc -> arc.getFirstId().equals(source)).mapToInt(ArcWithFlow::getFlow).sum();
  518.     }
  519.  
  520.     public Set<List<Arc>> getAllWays(Integer from, Integer to){
  521.         Set<List<Arc>> allWays = new HashSet<>();
  522.         recourseForAllWays(from, to, new ArrayList<>(), allWays);
  523.         return allWays;
  524.     }
  525.  
  526.     private boolean recourseForCycle(Integer id, List<Integer> vertexesList){
  527.         for (Integer index:
  528.                 vertexHashMap.get(id).getArcs().keySet()) {
  529.             if(vertexesList.contains(index)) {
  530.                 return true;
  531.             }
  532.             else{
  533.                 vertexesList.add(index);
  534.                 recourseForCycle(index, vertexesList);
  535.             }
  536.         }
  537.         return false;
  538.     }
  539.  
  540.     private void recourseForAllWays(Integer from, Integer to, List<Arc> way, Set<List<Arc>>allWays){
  541.         outer:
  542.         for (Integer id:
  543.                 vertexHashMap.get(from).getArcs().keySet()) {
  544.             for (Arc arc:
  545.                  way) {
  546.                 if(arc.getFirstId().equals(id)
  547.                         ||arc.getSecondId().equals(id))
  548.                     continue outer;
  549.             }
  550.             if(id.equals(to)){
  551.                 way.add(new Arc(from, id, vertexHashMap.get(from).getArcs().get(id)));
  552.                 allWays.add(copyWay(way));
  553.                 way.remove(way.size()-1);
  554.             }
  555.             else {
  556.                 way.add(new Arc(from, id, vertexHashMap.get(from).getArcs().get(id)));
  557.                 recourseForAllWays(id, to, way, allWays);
  558.                 way.remove(way.size()-1);
  559.             }
  560.         }
  561.     }
  562.  
  563.     private List<Arc> copyWay(List<Arc> way){
  564.         List<Arc> copyWay = new ArrayList<>();
  565.         way.forEach(arc -> copyWay.add(new Arc(arc.getFirstId(), arc.getSecondId(), arc.getWeight())));
  566.         return copyWay;
  567.     }
  568.  
  569.     private void recourseForConnectivityComponents(Integer id, List<Integer> vertexes, Set<Integer> component){
  570.         if(vertexes.contains(id)){
  571.             List<Integer> vertexesList = getVertexesList();
  572.             vertexes.remove(id);
  573.             component.add(id);
  574.             vertexHashMap.get(id).getArcs().forEach((index, weight)-> {
  575.                 if(hasAWay(index, id, vertexesList)){
  576.                     recourseForConnectivityComponents(index, vertexes, component);
  577.                 }
  578.             });
  579.         }
  580.     }
  581.  
  582.     private HashMap<Integer,Vertex> cloneGraph(HashMap<Integer,Vertex> otherGraph){
  583.         HashMap<Integer,Vertex> vertexMap = new HashMap<>();
  584.  
  585.         otherGraph.forEach((id,vertex)->{
  586.             Vertex vertex1 = new Vertex(id);
  587.             vertex.getArcs().forEach(vertex1::addArc);
  588.             vertexMap.put(id, vertex1);
  589.         });
  590.         return vertexMap;
  591.     }
  592.  
  593.     public void initGraph(String fileName){
  594.         try(BufferedReader fin=new BufferedReader(new FileReader(fileName)))
  595.         {
  596.             List<String> lines = fin.lines().collect(Collectors.toUnmodifiableList());
  597.  
  598.             for (String line:
  599.                  lines) {
  600.                 if(line.contains(">")){
  601.                     if(line.contains("(")){
  602.                         typeOfGraph = TypeOfGraph.ORIENTEERING_WITH_WEIGHTS;
  603.                         break;
  604.                     }
  605.                     else{
  606.                         typeOfGraph = TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS;
  607.                         break;
  608.                     }
  609.                 }
  610.                 else{
  611.                     if(line.contains("(")){
  612.                         typeOfGraph = TypeOfGraph.NOT_ORIENTEERING_WITH_WEIGHTS;
  613.                         break;
  614.                     }
  615.                     else{
  616.                         typeOfGraph = TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS;
  617.                     }
  618.                 }
  619.             }
  620.  
  621.             if(TypeOfGraph.NOT_ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)||
  622.                     TypeOfGraph.ORIENTEERING_WITHOUT_WEIGHTS.equals(typeOfGraph)) {
  623.                 lines.forEach(this::initWithOutWeight);
  624.             }
  625.             else{
  626.                 lines.forEach(this::initWithWeight);
  627.             }
  628.         }
  629.         catch(IOException ex){
  630.             throw new IllegalArgumentException("Ошбка чтения файла");
  631.         }
  632.     }
  633.  
  634.     public Graph UIGetMinOstTreeBorvki(){
  635.         Graph graph = new Graph(typeOfGraph);
  636.         getVertexesList().forEach(graph::addVertex);
  637.  
  638.         controller.printVertexes();
  639.         try {
  640.             Thread.sleep(2000);
  641.         } catch (InterruptedException e) {
  642.             e.printStackTrace();
  643.         }
  644.         while (true){
  645.             List<Set<Integer>> components = graph.getConnectivityComponents();
  646.             if(components.size()==1)
  647.                 break;
  648.             components.forEach(set->{
  649.                 AtomicInteger min = new AtomicInteger(Integer.MAX_VALUE);
  650.                 AtomicInteger minIdFrom = new AtomicInteger(Integer.MIN_VALUE);
  651.                 AtomicInteger minIdTo = new AtomicInteger(Integer.MIN_VALUE);
  652.                 set.forEach(vertex-> vertexHashMap.get(vertex).getArcs().forEach((id, weight)->{
  653.                     if(!set.contains(id) && weight< min.get()){
  654.                         min.set(weight);
  655.                         minIdFrom.set(vertex);
  656.                         minIdTo.set(id);
  657.                     }
  658.                 }));
  659.                 if(!graph.vertexHashMap.get(minIdTo.get()).getArcs().containsKey(minIdFrom.get())){
  660.                     graph.addArcWithWeight(minIdFrom.get(), minIdTo.get(), min.get());
  661.                     controller.printArc(minIdFrom.get(), minIdTo.get());
  662.                 }
  663.  
  664.             });
  665.             try {
  666.                 Thread.sleep(2000);
  667.             } catch (InterruptedException e) {
  668.                 e.printStackTrace();
  669.             }
  670.         }
  671.         return graph;
  672.     }
  673.  
  674.     private void initWithWeight(String line){
  675.         StringBuilder strFirstId = new StringBuilder();
  676.         StringBuilder strSecondId = new StringBuilder();
  677.         StringBuilder strWeight = new StringBuilder();
  678.         boolean twoVertex = true;
  679.  
  680.         outerLoop:
  681.         for(int i = 0; i < line.length(); i++){
  682.             while(Character.isDigit(line.charAt(i))){
  683.                 strFirstId.append(line.charAt(i));
  684.                 if(i == line.length() - 1){
  685.                     twoVertex = false;
  686.                     break outerLoop;
  687.                 }
  688.                 i++;
  689.             }
  690.             i++;
  691.             while(Character.isDigit(line.charAt(i))){
  692.                 strSecondId.append(line.charAt(i));                  //ОЧЕНЬ ПЛОХО, НО КОНКАТЕНАЦИЯ НЕ РАБОТАЕТ(НЕ ЗНАЮ ПОЧЕМУ)
  693.                 i++;
  694.             }
  695.             i++;
  696.             while(Character.isDigit(line.charAt(i))){
  697.                 strWeight.append(line.charAt(i));                  //ОЧЕНЬ ПЛОХО, НО КОНКАТЕНАЦИЯ НЕ РАБОТАЕТ(НЕ ЗНАЮ ПОЧЕМУ)
  698.                 i++;
  699.             }
  700.         }
  701.  
  702.         int firstId = Integer.parseInt(strFirstId.toString());
  703.         if(twoVertex){
  704.             int secondId = Integer.parseInt(strSecondId.toString());
  705.             int weight = Integer.parseInt(strWeight.toString());
  706.  
  707.             AtomicBoolean first = new AtomicBoolean(false);
  708.             AtomicBoolean second = new AtomicBoolean(false);
  709.             vertexHashMap.forEach((index, vertex) ->{
  710.                 if(vertex.getId() == firstId){
  711.                     first.set(true);
  712.                 }
  713.                 else if(vertex.getId() == secondId){
  714.                     second.set(true);
  715.                 }
  716.             });
  717.             if(!first.get()) {
  718.                 addVertex(firstId);
  719.             }
  720.             if(!second.get()) {
  721.                 addVertex(secondId);
  722.             }
  723.             addArcWithWeight(firstId,secondId,weight);
  724.         }
  725.         else{
  726.             addVertex(firstId);
  727.         }
  728.     }
  729.  
  730.     private void initWithOutWeight(String line){
  731.         StringBuilder strFirstId = new StringBuilder();
  732.         StringBuilder strSecondId = new StringBuilder();
  733.         boolean twoVertex = true;
  734.  
  735.         outerLoop:
  736.         for(int i = 0; i < line.length();){
  737.             while(Character.isDigit(line.charAt(i))){
  738.                 strFirstId.append(line.charAt(i));                  //ОЧЕНЬ ПЛОХО, НО КОНКАТЕНАЦИЯ НЕ РАБОТАЕТ(НЕ ЗНАЮ ПОЧЕМУ)
  739.                 if(i == line.length() - 1){
  740.                     twoVertex = false;
  741.                     break outerLoop;
  742.                 }
  743.                 i++;
  744.             }
  745.             i++;
  746.             while(Character.isDigit(line.charAt(i))){
  747.                 strSecondId.append(line.charAt(i));                  //ОЧЕНЬ ПЛОХО, НО КОНКАТЕНАЦИЯ НЕ РАБОТАЕТ(НЕ ЗНАЮ ПОЧЕМУ)
  748.                 if(i == line.length() - 1){
  749.                     break outerLoop;
  750.                 }
  751.                 i++;
  752.             }
  753.         }
  754.  
  755.         int firstId = Integer.parseInt(strFirstId.toString());
  756.         if(twoVertex){
  757.             int secondId = Integer.parseInt(strSecondId.toString());
  758.             AtomicBoolean first = new AtomicBoolean(false);
  759.             AtomicBoolean second = new AtomicBoolean(false);
  760.             vertexHashMap.forEach((index, vertex) ->{
  761.                 if(vertex.getId() == firstId){
  762.                     first.set(true);
  763.                 }
  764.                 else if(vertex.getId() == secondId){
  765.                     second.set(true);
  766.                 }
  767.             });
  768.             if(!first.get()) {
  769.                 addVertex(firstId);
  770.             }
  771.             if(!second.get()) {
  772.                 addVertex(secondId);
  773.             }
  774.             addArc(firstId, secondId);
  775.         }
  776.         else{
  777.             addVertex(firstId);
  778.         }
  779.     }
  780. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement