Advertisement
dmestanza369

Untitled

Dec 3rd, 2021
640
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. import java.util.HashSet;
  2. import java.util.LinkedList;
  3. import java.util.Queue;
  4. import java.util.Scanner;
  5.  
  6. class Nodo {
  7.     int x, nivel;
  8.     Nodo(int x, int nivel) {
  9.         this.x = x;
  10.         this.nivel = nivel;
  11.     }
  12. }
  13.  
  14. public class AER319 {
  15.  
  16.     public static int bfs(Nodo root, int fin) {
  17.         Nodo temp = root;
  18.         Queue<Nodo> cola = new LinkedList<>();
  19.         cola.add(temp);
  20.         HashSet<Integer> respuestas = new HashSet<>();
  21.         respuestas.add(temp.x);
  22.  
  23.         while(temp.x != fin) {
  24.             temp = cola.remove();
  25.             Nodo h1 = new Nodo((temp.x+1) % 10000, temp.nivel+1);
  26.             if (!respuestas.contains(h1.x)){
  27.                 cola.add(h1);
  28.                 respuestas.add(h1.x);
  29.             }
  30.             Nodo h2 = new Nodo((temp.x*2) % 10000, temp.nivel+1);
  31.             if (!respuestas.contains(h2.x)){
  32.                 cola.add(h2);
  33.                 respuestas.add(h2.x);
  34.             }
  35.             Nodo h3 = new Nodo((temp.x/3) % 10000, temp.nivel+1);
  36.             if (!respuestas.contains(h3.x)){
  37.                 cola.add(h3);
  38.                 respuestas.add(h3.x);
  39.             }
  40.         }
  41.         return temp.nivel;
  42.     }
  43.     public static void main(String[] args) {
  44.         Scanner sc = new Scanner(System.in);
  45.         while (sc.hasNext()){
  46.             int inicio = sc.nextInt();
  47.             int fin = sc.nextInt();
  48.  
  49.             Nodo padre = new Nodo(inicio, 0);
  50.             int sol = bfs(padre, fin);
  51.             System.out.println(sol);
  52.         }
  53.         sc.close();
  54.     }
  55.  
  56.    
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement