Friday, 23 December 2011

Min moves to move Knight from one grid to another on a NxN Chess board.



TO find the minimum moves required to move a Knight on a NxN chess board
from position (x,y) to (a,b).

The problem is solved using Graphs. The min number of moves can be computed with running BFS on graph generated with NxN nodes. The adjacency between the vertexesof the graph is computed using the movement of the horse.

Try running the Computation of Adjacency and min distance code online:http://codepad.org/yZDbgECz
N=8 and the vertexes are numbered in the below order.
  00 01 02 03 04 05 06 07
  08 09 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 58 59 60 61 62 63  

#include <iostream>
#include <queue>
using namespace std;
#define GRID 8
#define ADJMATRIX 64 //(GRID*GRID)
/***************************************************************************
TO find the minimum moves required to move a Knight on a NxN chess board
from position (x,y) to (a,b).

Note: 
Assumption =for a 8x8 matrix (x,y) range is (0,0) to (7,7).

Author: Thejas P M

*****************************************************************************/
class Node
{
 public:
  int Dist;
  Node(int d=0)
  {
      Dist=d;
  }
};

void possibleKnightMoves(int x, int y,Node arr[64][64])
{
    int xPlus2 = x+2;
    int xMinus2 = x-2;
    int xPlus1 = x+1;
    int xMinus1 = x-1;
    int yPlus2 = y+2;
    int yMinus2 = y-2;
    int yPlus1 = y+1;
    int yMinus1 = y-1;
    int current = y*GRID+x;
    arr[current][current].Dist=0;
    if(xPlus2 < GRID && yPlus1 < GRID)
    {
        int adjVtx = yPlus1*GRID+xPlus2;
        arr[current][adjVtx].Dist=1;
    }
    if(xPlus2 < GRID && yMinus1 >= 0)
    {
        int adjVtx = yMinus1*GRID+xPlus2;
        arr[current][adjVtx].Dist=1;
    }

    if(xMinus2 >= 0 && yPlus1 < GRID)
    {
        int adjVtx = yPlus1*GRID+xMinus2;
        arr[current][adjVtx].Dist=1;
    }
    if(xMinus2 >= 0 && yMinus1 >= 0)
    {
        int adjVtx = yMinus1*GRID+xMinus2;
        arr[current][adjVtx].Dist=1;
    }

    if(xPlus1 < GRID && yPlus2 < GRID)
    {
        int adjVtx = yPlus2*GRID+xPlus1;
        arr[current][adjVtx].Dist=1;
    }
    if(xPlus1 < GRID && yMinus2 >= 0)
    {
        int adjVtx = yMinus2*GRID+xPlus1;
        arr[current][adjVtx].Dist=1;
    }

    if(xMinus1 >= 0 && yPlus2 < GRID)
    {
        int adjVtx = yPlus2*GRID+xMinus1;
        arr[current][adjVtx].Dist=1;
    }
    if(xMinus1 >= 0 && yMinus2 >= 0)
    {
        int adjVtx = yMinus2*GRID+xMinus1;
        arr[current][adjVtx].Dist=1;
    }
    return;
}


int** BFSAdj(Node arr[64][64], int& vtx,int& vtxCount)
{
    /*
        Step 1: Colour all the nodes in the Storage structure as White(0) and parents to -1
        Step 2: Start with the vtx passed onto the function set its Distance to 0 i.e Storage[vtx][2]=0
        Step 3: Initialize a Queue, ENQUE the vtx onto Q
        Step 4: While Queue not empty do
                    Let VtxTemp = DEQUE from Q
                    Let S array = all Vertexes Adjacent to VtxTemp
                    For each vertex in S array
                        if Storage[Si][0] == White
                            Change colour    Storage[Si][0] == Grey
                            Update Distance  Storage[Si][2] == Storage[VtxTemp][2] + 1
                            Update parent    Storage[Si][2] = VtxTemp
                            ENQUE Si
                    Storage[VtxTemp][1]=2
        Step 5: Done

    */
    if(vtxCount <=0 || vtx > vtxCount)
    {
        cout<<"CHECK the INPUT TO BFS"<<endl;
        return NULL;
    }

    int **Storage = NULL;
    Storage = new int*[vtxCount];
    int i=0;
    for(i=0;i<vtxCount;++i)
    {
        Storage[i]=new int[3];
        Storage[i][0]=0; //holds the colour of the node 0-White,1-Grey,2-Black
        Storage[i][1]=-1; //Parent Node
        Storage[i][2]=99; //Distance
        //cout<<Storage[i][0]<<endl<<Storage[i][1]<<endl<<Storage[i][2]<<endl<<endl;
    }

    Storage[vtx][2]=0;
    int array[64];
    int temp_count=0;
    std::queue<int> bfsQ;
    bfsQ.push(vtx);
    while(bfsQ.size() > 0)
    {
        int vtxTemp = bfsQ.front();
        array[temp_count++]=vtxTemp;
        bfsQ.pop();
     /*   Node *sArray =arr[vtxTemp-1].next;

        while (sArray != NULL)
        {
            if(Storage[sArray->value-1][0] == 0)//white
            {cout<<"sArray->value="<<sArray->value<<endl;
                Storage[sArray->value-1][0]=1;
                Storage[sArray->value-1][1]=vtxTemp;
                Storage[sArray->value-1][2]=Storage[vtxTemp-1][2] + 1;
                bfsQ.push(sArray->value);
                cout<<Storage[sArray->value-1][0]<<"  "<<Storage[sArray->value-1][1]<<"  "<<Storage[sArray->value-1][2]<<endl<<endl;
            }
            sArray=sArray->next;
        }
*/
        for(int j=0;j<ADJMATRIX;++j)
        {
            if(arr[vtxTemp][j].Dist==1)
            {

                 if(Storage[j][0] == 0)//white
                    {
                        cout<<"vtxTemp,j="<<vtxTemp<<","<<j<<endl;
                        Storage[j][0]=1;
                        Storage[j][1]=vtxTemp;
                        Storage[j][2]=Storage[vtxTemp][2] + 1;
                        bfsQ.push(j);
                        //cout<<" "<<j;
                        // cout<<"-----"<<j<<"------"<<endl<<Storage[j][0]<<"\n"<<Storage[j][1]<<" \n"<<Storage[j][2]<<endl<<endl;
                    }
            }
        }
        Storage[vtxTemp][0]=2;
    }
    //Print nodes the entered the Q
    /*cout<<"\nPOP ORDER\n";
    for(int i=0;i<temp_count;++i)
        cout<<" "<<array[i];
    cout<<"\n";*/
    return Storage;
}

int getMove(int** res,int vtxSource,int vtxDst)
{
    cout<<"\n PATH = "<<vtxDst<<"<==";
    if(res[vtxDst][2]==99)
    {
        return -1;
    }
    int result=res[vtxDst][2];
    while(res[vtxDst][1]!=-1)
    {
        vtxDst=res[vtxDst][1];
        cout<<vtxDst<<"<==";
    }
    cout<<endl;
    return result;
}

/*NxN Knight shortest path / Min moves
  There are NxN nodes in total
  two nodes [(x,y) and (a,b)] are connected
  if a,b < GRID and (a,b) is in
  {(x+1,y+2),(x+1,y-2),(x+2,y+1),(x+2,y-1),(x-2,y-1),(x-2,y+1),(x+2,y+1),(x+1,y-1)}
  the nodes are numbered in this order

  00 01 02 03 04 05 06 07
  08 09 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 58 59 60 61 62 63


  The conversion from the x,y cordinates to the nodes Formula [vertex = (x*GRID+j)]
  similarly x,y =

*/
int main()
{
  Node arr[ADJMATRIX][ADJMATRIX];

    for(int i=0;i<GRID;++i)
    {
        for(int j=0;j<GRID;++j)
        {
            possibleKnightMoves(i,j,arr);
        }
    }

    int x = 7, y = 3,vtxSource = y*GRID+x;
    int xa = 7,ya=7,vtxDst=ya*GRID+xa,count =ADJMATRIX;

    int** resultSet= BFSAdj(arr,vtxSource,count);

    // Find min moves
    cout<<"ANSWER = "<<getMove(resultSet,vtxSource,vtxDst);

        //Print adjacencyMatrix
        /*for(int i=0;i<count;++i)
        {
            cout<<""<<i<<"\t";
        }
        cout<<endl<<endl;
        for(int i=0;i<count;++i)
        {
            for(int j=0;j<count;++j)
            {
                cout<<arr[i][j].Dist<<"\t";
            }
            cout<<endl;
        }*/

        //PRINT BFS MATRIX
        /*    cout<<" --- Result --"<<endl;
            for(int i=0;i<count;++i)
            {
                cout<<"a["<<i<<"]\t";
            }
            cout<<endl;
            for(int j=0;j<3;++j)
            {

                for(int i=0;i<count;++i)
                {
                    cout<<resultSet[i][j]<<"\t\t";
                }
                cout<<endl;
            }
        */

    return 0;
}