Código algoritmo busca em profundidade - Design Pattern State

Post date: Oct 28, 2017 12:41:47 AM

 package state;  import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;  public class No {  private Set adjacentes = new HashSet<>();  private Cor cor;  private String name;   public No(String name) {   this.name = name;   cor = new Branco();  }   public void buscaProfundidade(List list) {   cor.busca(this, list);  }   public Set getAdjacentes() {   return adjacentes;  }   public void addAdjacentes(No adj) {   adjacentes.add(adj);  }   public void setCor(Cor cor, List list) {   this.cor = cor;   cor.assumiu(this, list);  }   public String toString() {   return name;  }   public static void main(String[] args) {   No a = new No("A");   No b = new No("B");   No c = new No("C");   No d = new No("D");   No e = new No("E");   No f = new No("F");   No g = new No("G");   No h = new No("H");   a.addAdjacentes(b);   a.addAdjacentes(e);   a.addAdjacentes(h);    b.addAdjacentes(c);    c.addAdjacentes(d);    d.addAdjacentes(b);    e.addAdjacentes(f);    f.addAdjacentes(c);   f.addAdjacentes(g);   f.addAdjacentes(h);    List l = new ArrayList<>();   a.buscaProfundidade(l);   for (No n : l)    System.out.println(n);  } }   package state;  import java.util.List;  public abstract class Cor {  void busca(No no, List list) {  }   void assumiu(No no, List list) {  } }   package state;  import java.util.List;  public class Branco extends Cor {  public void busca(No no, List list) {   no.setCor(new Cinza(), list);  } }   package state;  import java.util.List;  public class Cinza extends Cor {  void assumiu(No no, List list) {   System.out.println("Nó " + no + " ficou cinza");   for (No adj : no.getAdjacentes())    adj.buscaProfundidade(list);   no.setCor(new Preto(), list);  } }   package state;  import java.util.List;  public class Preto extends Cor {  void assumiu(No no, List list) {   System.out.println("Nó " + no + " ficou preto");   list.add(no);  } }