GeeksforGeeks » Algorithms

Software Engineer

(3 posts)
  • Started 5 months ago by NameLess
  • Latest reply from Dixit Sethi
  1. NameLess
    guest
    Posted 5 months ago #

    write an algorithm to compute the number of possible path(permutation based on the position of knight) to a Knight in the given board.
    Initial position of knight is at '0'

     given board
    
       1   2  3
       4   5  6
       7   8  9
            0
    
    int findNoOfPaths(board b, initial position){
       --
        --
    }
    

    example: the number of possible paths/permutation of length 1(one) is=2{04,06}
    the number of possible paths/permutation of length 2(two) is 6={043,049,040,067,061,060}

  2. kapil
    guest
    Posted 5 months ago #

    I think path length should also be an input parameter., otherwise there will be infinite paths of diferent lengths. Let me know if my thinking of question is correct.

  3. Dixit Sethi
    Member
    Posted 5 months ago #

    Here is the idea:
    there are two positions for each no. where a knight can go except 4 and 6 which have 3 positions each(0,3,9 and 0,1,7). So a tree can be formed with each no. having two children which can be next position from that no. for ex 1 will have child 6 and 8, 3 will have 4 and 8, 4 will have 3 and 9 (keeping 0 aside) and 6 will have 1 and 7. An array can be formed as

    a={0,1,2,3,4,5,6,7,8,9,4,6,8,6,7,9,8,4,9,3,-1,-1,1,7,6,2,1,3,4,2} where a[0] to a[9] denotes the 10 positions knight can have, and a[11] to a[29] denotes the children of first 10 nos. a[i] have children a[10+2i] and a[11+2i], i=0 to 9. '5' position can't be taken by knight so its children are -1. The case of 0 as child of 4 and 6 is included separately in program.

    Now use recursion and count the no of paths knight can take by proceeding on to next levels by taking children at one stage as positions at next stage.

    The following program does this:

    #include<stdio.h>
    #include<conio.h>
    int my_func(int*,int,int);
    void main()
    {
    int a[]={0,1,2,3,4,5,6,7,8,9,4,6,8,6,7,9,8,4,9,3,-1,-1,1,7,6,2,1,3,4,2};
    int len,nop,loc;
    len=0;
    while(getch()!='n')
    {
    printf("enter no of permutation \t");
    scanf("%d",&nop);
    loc=0;
    len=my_func(&a,nop,loc);
    printf("\nlast len=%d",len);
    printf("\n");
    }
    }

    int my_func(int *a, int nop, int loc)
    {
    int n1,n2,n3,n;
    n1=n2=n3=1;

    nop--;
    if(nop>0)
    {

    n1=my_func(a,nop,*(a+10+2*loc));

    n2=my_func(a,nop,*(a+11+2*loc));

    if(*(a+loc)==4 || *(a+loc)==6)
    n3=my_func(a,nop,0);
    }
    n=n1+n2;
    if(loc==4 || loc==6)
    n+=n3;
    return(n);
    }


Reply

You must log in to post.

RSS feed for this topic