Tuesday, June 28, 2016

Given a chess board of finite length, start a position of a knight, an end position 
  • Find whether the end position is reachable by the knight 
  • Number of minimum hops required to reach that position 

One solution is to use backtracking: 
void GetMinMoves(Point start, Point end, int count, ref int min) 
{ 
 if ( start == end) { if (count < min), {min = count;} } 
 var x = new List<int>() { 2, 1, -1, -2, -2, -1,  1,  2}; 
 var y = new List<int>() { 1, 2,  2,  1, -1, -2, -2, -1}; 
for (int k =0 ; k < 8; k ++) 
{ 
   start.x += x[k]; 
   start.y += y[k]; 
   if (isValid(start)) 
       GetMinMoves(start, end, count + 1, ref min); 
   start.x -= x[k]; 
   start.y -= y[k]; 
} 
} 
// isValid checks for both whether the position is on the board and if it has been visited. 
Another is to use breadth first traversal: 
Define the edges in such a graph and the ways when you can travel from vertex I to vertex j. Once we have the graph, it reduces to finding the shortest path in an unweighted graph.  
Int knightMoves (point[,] board, int N, point x, point y) 
{ 
Add the starting point to a queue 
While queue is not empty 
     Extract a point 
     If point == destination return 
     If point already visited continue 
     For each of eight moves the knight can make 
        Enqueue the point 

Return -1; 
} 

In a binary search tree two nodes are out of order. Find them
Here the inorder traversal will find elements tgat are not in the sorted order. However there may be rwo of tgose tgat are lesser than their previous value or there may just be one. In the latter case, tge two nodes that are out of order are adjacent in tge inorder traversal.

Void findBSTHelper(node root, ref node prev, ref node cur, ref node next, ref node last)
{
If root == null return;
FindBSTHelper( root.left, ref prev, ref cur, ref next, ref last);
If (prev && prev.data < root.data){
If(!first){
First = prev;
Cur = root:
}else{
last = root;
}

}
Prev = root;
}

FindBSTHelper( root.right, ref prev, ref cur, ref next, ref last);
}
Swap first and last or swap first and middle

No comments:

Post a Comment