Alternative to backtracking and to speed up program

588 views Asked by At

I was trying to make a knights tour problem solution and i have just made it. Now i want to improve it.It takes the starting value and then outputs the step by step instructions to move (in command line output).

Now the technique which i have used is that firstly i have divided the board into 4 blocks according to the solution given in a video (here www.youtube.com%2Fwatch%3Fv%3DdWM5pKYZCHw&b=28) and also divided the whole board into 4 systems of boxes.

In the solution i have to do do lots of backtracking to decide between two different possibilities which greatly reduces the speed.Is there any way to do less or no backtracking to decide between two possibilities. And any other suggestion to improve the technique. Here is a part of the code (a function which moves the knight across the board)

void move(int l[8][8][2],int g, int e)  // g and e are the required systems and blocks respectively
{
      backtracking(backtrackarray, l); // calling function to backtrack the array

      backtracking(secondbacktrackarray,l);    againcalling function to backtrack array in different array

      int system = currentsystem(l, currentposition[0], currentposition[1]); //storing the current system

      for (int i = 0; i < 3; i++)
      {
          nextmove(l, currentposition[0], currentposition[1]);  //moving knight

      }

      if (blockshiftpossible(l, system, currentposition[0], currentposition[1])!= 1) // checks if next block shift possible
      {
           backimage(l, backtrackarray); getting back the stored image 

           for (int i = 0; i < 3; i++)
           {
              reversenextmove(l, currentposition[0], currentposition[1]); // moving in the opposite way
           }

      }

      if ((systemshiftpossible(l, currentposition[0], currentposition[1])!= 1) && (g==4) && (e==4)) // checking if system shift is possible

      { 
            backimage(l,secondbacktrackarray); // getting again image from second backtrack array

            for (int i = 0; i < 3; i++)
            {

                 reversenextmove(l, currentposition[0], currentposition[1]);  // moving in opposite direction

            }

            if (systemshiftpossible(l, currentposition[0], currentposition[1])!= 1)
            {

                  for (int i = 0; i < 3; i++)
                  {
                     nextmove(l, currentposition[0], currentposition[1]);

                   }
             }
      }


      if ((blockshiftpossible(l, system, currentposition[0], currentposition[1])
        == 1) && (g!=4))

      {

            blockshift(l, currentposition[0], currentposition[1]);

      }

      else

      {

        cout << "logical error"<<endl;

      } 

}

To see the details of this technique check my previous question Solving knight tour with c++

Also how i can change it to get solutions for n*n puzzles if possible.

0

There are 0 answers