i have also a problem with this i am using backtracking but i don't know it doesn't work right it take alot of time it is an ACM problem here is the code please if anyone have any idea what is wrong in this code please inform
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
struct Square
{
int Row, IColumn;
char Column;
}Source, Target;
int count1;
bool Visited[9][9];
vector<int> MinNumberOfKnightMoves;
int NRow[] = {-2, -2, -1, -1, 1, 1, 2, 2};
int NColumn[] = {-1, 1, -2, 2, -2, 2, -1, 1};
bool isValid(int Row, int Column)
{
return (Row > 0 && Row < 9 && Column > 0 && Column < 9);
}
void KnightMoves(int NumberOfMoves, int Row, int Column)
{
if(NumberOfMoves==64)
return;
if(Row == Target.Row && Column == Target.IColumn)
{
MinNumberOfKnightMoves.push_back(NumberOfMoves);
return;
}
for(int i = 0; i < 8; i ++)
{
if(isValid( Row + NRow[i], Column + NColumn[i]) && !Visited[ Row + NRow[i]][Column + NColumn[i]])
{
Visited[Row][Column] = true;
KnightMoves(NumberOfMoves + 1, Row + NRow[i], Column + NColumn[i]);
Visited[Row][Column] = false;
}
}
}
int main()
{
string square;
while(cin >> square)
{ count1 =0;
Source.Column = square[0];
Source.IColumn = square[0] - 'a' + 1;
Source.Row = square[1] - '0';
cin >> square;
Target.Column = square[0];
Target.IColumn = square[0] - 'a' + 1;
Target.Row = square[1] - '0';
for(int i = 0; i < 9; i ++)
for(int j = 0; j < 9; j ++)
Visited[i][j] = false;
KnightMoves(0, Source.Row, Source.IColumn);
sort(MinNumberOfKnightMoves.begin(), MinNumberOfKnightMoves.end());
cout << "To get from " << Source.Column << Source.Row << " to "
<< Target.Column << Target.Row <<" takes "
<< MinNumberOfKnightMoves[0] << " knight moves." << endl;
MinNumberOfKnightMoves.clear();
}
return 0;
}