The knights journey where we are given the start, end points and the size of board.find the minimum steps to reach the end from the starting point.
i tried doing it with dfs but was clearly failed .
and the searched the solution online where they used bfs to solve the ques .
int count(vector<vector>&board,int a,int b,int x,int y,int n){
if (a>=n or b>=n or b<0 or a<0 or board[a][b]==1 )return 500;
if (a==x and b==y)return 0;
board[a][b]=1;
int one =count(board,a+2,b+1,x,y,n)+1;
int two =count(board,a+2,b-1,x,y,n)+1;
int three =count(board,a-2,b+1,x,y,n)+1;
int four =count(board,a-2,b-1,x,y,n)+1;
int five =count(board,a+1,b+2,x,y,n)+1;
int six =count(board,a+1,b-2,x,y,n)+1;
int seven =count(board,a-1,b+2,x,y,n)+1;
int eight =count(board,a-1,b-2,x,y,n)+1;
board[a][b]=0;
int minMoves = min({one, two, three, four, five, six, seven, eight});
return minMoves;
}
int minMovesRequired(int n, Cell start, Cell end) {
vector<vector<int>>board(n,vector<int>(n,0));
int a=start.x;
int b=start.y;
int c=end.x;
int d=end.y;
int ans=count(board,a,b,c,d,n);
return (ans >= 1000) ? -1 : ans;
}sorry for the terrible code how should i even approach this ques and plz explain why this is wrong .plz help.
new is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.