Directi Interview Question
Software Engineer / DevelopersYou can approach the problem in the following way -
Construct a Directed Graph where max No of jumps will be the no of leaving edges from that specific node.After constructing the Graph do a BFS tree traversal,u will get the min path and to find all possible path modify the standard BFS algo....
Simple code to find out if its reachable :
#include<stdio.h>
int jump(int a,int b)
{
return a+b;
}
void Func(int n,int a[n],int start,int last)
{
int i,k=0,temp;
while(k<n)
{
for(i=1;i<=a[k];i++)
{
temp=jump(k,i);
if(temp==last)
{
printf("Reachable\n");
return;
}
}
k++;
}
printf("Not reachable\n");
return;
}
main()
{
int n,i;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
Func(n,a,0,n-1);
}
Backtracking + Recursion :
1). If the last index was reachable from the first index.
n=1
Take jumps of n, if current number is 0, backtrack and jump n+1 if possible, else backtrack. If you reach the end, then print reachable.
2). Minimum number of jumps required to reach the last index, given any index as the starting index.
n = biggest possible step
Take jumps of n, if current number is 0, backtrack and jump n-1 if possible, else backtrack. Keep a count of jumps.
3). Total number of ways one can reach the last index.
Aha ! variation of (1), when you reach end, do not exit from the program, rather increase the count. so you will get the count of all possible ways to reach the end.
i think this code is working..
#include<stdio.h>
int n,s[100];
int min(int a,int b)
{
return(a<b?a:b);
}
int fun(int i,int count)
{
int j,max1=n+1;
if(i>=n)
{
return max1;
}
else
{
if(i==n-1)
{
return count;
}
for(j=1;j<=s[i];j++)
{
max1=min(max1,fun(i+j,count+1));
}
}
return max1;
}
main()
{
int i;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&s[i]);
}
if((i=fun(0,0))==n+1)
{
printf("\ncould not reachable");
}
else
{
printf("\n\n\nreachable in %d steps ",i);
}
}
Using BFS :
private static int BFS(Queue<Node> q) {
while(!q.isEmpty()) {
Node node = q.remove();
int curInd = node.getIndex();
int curJump = node.getJump();
if(curInd == N)
return curJump;
int value = node.getValue();
for(int i = 1; i <= value; ++i) {
int index = curInd+i;
int jump = curJump+1;
if(isSafe(nodes, index)) {
nodes[index].setColor(COLOR.GREY);
nodes[index].setJump(jump);
nodes[index].setParent(curInd);
q.add(nodes[index]);
}
}
node.setColor(COLOR.BLACK);
}
return -1;
}
private static int getMinJump(Node[] nodes, int start, int end) {
Queue<Node> q = new LinkedList<Node>();
nodes[start].setColor(COLOR.GREY);
nodes[start].setJump(0);
nodes[start].setParent(-1);
q.add(nodes[start]);
return BFS(q);
}
private static boolean isSafe(Node[] nodes, int index) {
return index >= 1 && index <= N && nodes[index].getColor() == COLOR.WHITE;
}
Think of Dynamic Programming
- Anonymous January 14, 2010