forked from golumall/Graph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvert_X_Y.java
More file actions
57 lines (54 loc) · 1.06 KB
/
Copy pathConvert_X_Y.java
File metadata and controls
57 lines (54 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.Scanner;
import java.util.HashSet;
import java.util.Set;
import java.util.Queue;
import java.util.LinkedList;
class Graph
{
int val;
int steps;
Graph(int val,int steps)
{
this.val=val;
this.steps=steps;
}
}
class Convert_X_Y
{
static int steps(int src,int dest)
{
Set<Graph> visited=new HashSet<>(10000);
Queue<Graph> q=new LinkedList<>();
Graph node=new Graph(src,0);
q.add(node);
visited.add(node);
while(!q.isEmpty())
{
Graph temp=q.poll();
visited.add(temp);
if(temp.val==dest)
return temp.steps;
int mul=temp.val*2;
int sub=temp.val-1;
//Given Constrains
if(mul>0&&mul<10000)
{
Graph x=new Graph(mul,temp.steps+1);
q.add(x);
}
if(sub>0&&sub<10000)
{
Graph y=new Graph(sub,temp.steps+1);
q.add(y);
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int src=sc.nextInt();
int dest=sc.nextInt();
System.out.println(steps(src,dest));
}
}
//https://www.geeksforgeeks.org/minimum-number-operation-required-convert-number-x-y/