-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimumSteps.java
More file actions
49 lines (37 loc) · 1.22 KB
/
minimumSteps.java
File metadata and controls
49 lines (37 loc) · 1.22 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
/*Minimum steps to the destination */
class GFG
{
//https://www.geeksforgeeks.org/minimum-steps-to-reach-a-destination/
// Function to count number of steps
// required to reach a destination
// source -> source vertex
// step -> value of last step taken
// dest -> destination vertex
static int steps(int source, int step,
int dest)
{
// base cases
if (Math.abs(source) > (dest))
return Integer.MAX_VALUE;
if (source == dest)
return step;
// at each point we can go either way
// if we go on positive side
int pos = steps(source + step + 1,
step + 1, dest);
// if we go on negative side
int neg = steps(source - step - 1,
step + 1, dest);
// minimum of both cases
return Math.min(pos, neg);
}
// Driver Code
public static void main(String[] args)
{
int dest = 11;
System.out.println("No. of steps required"+
" to reach " + dest +
" is " + steps(0, 0, dest));
}
}
//noIdea