Given a square chessboard, the initial position of Knight and position of a target. Find out the minimum steps a Knight will take to reach the target position.
Note: index are zero-based.
classSolution{ // There is only 8 possible way that a Knight can move within the chessboard. private (int,int)[] directions = [(-1,-2), (1,-2), (2,-1), (2,1), (1,2), (-1,2), (-2,1), (-2,-1)]; // Function to find out minimum steps Knight needs to reach target position.publicintMinStepToReachTarget(List<int> KnightPos,List<int> TargetPos,int N) {bool[,] visited =newbool[N, N];Queue<(int,int,int)> queue =newQueue<(int,int,int)>();queue.Enqueue((KnightPos[0],KnightPos[1],0));while (queue.Count>0) {var (x, y, dis) =queue.Dequeue();if (x ==TargetPos[0] && y ==TargetPos[1]) {return dis; }foreach ((int xP,int yP) in directions) { // move next stepint newX = x + xP;int newY = y + yP;if (newX >=0&& newX <= N && newY >=0&& newY <= N &&!visited[newX, newY]) {visited[newX, newY] =true;queue.Enqueue((newX, newY, dis +1)); } } }return-1; }}