Sunday, June 26, 2016

Today we discuss a few more coding problems :
Given a MXN matrix. To find the number of ways to reach the mth row and nth column cell from 0,0 cell. Find the same if some of the cells are marked as not reachable.
We can use backtracking here
void numPaths(int N, Point start, Point end, ref List<Point> paths, ref List<Point> candidate)
{
if (start == end) {paths.Add(candidate); return;}
for (int i = 0; i < 3; i++) // for one of three directions to take
{
var next = start.adjacents(i);
if (next.isValid() != true || next.isBlocked()) continue;
candidate.Add(next);
if (next == end) { paths.Add(candidate);}
if (next != end && candidate.Count < N)
      numPaths(next, end, ref paths, ref candidate);
candidate.RemoveLast();
}
Given a BST Find maximum k elements in a tree
We can do this with inorder traversal because it will list the elements in sorted order
void KLarge(node root, ref Queue<node> window)
{
if (root == null) return
KLarge(root.left, ref window)
if (window.Count < K){
    window.enqueue(root);
}else{
   window.dequeue();
   window.enqueue(root);
}
KLarge(root.right, ref window);
}
Incidentally we can do this in steps by finding the Kth largest element before finding the N-K elements
by doing a reverse inorder traversal
KthLargest(Node root, int k, ref int visited)
{
if (root == null || visited >= k) return;
KthLargest(root.right, k, visited);
visited++;
if (visited == k)
{
 print(root.data); 
}
KthLargest(root.left, k, visited);
}
or print the large k elements in descending order
void getKLarge(node root, ref int k)
{
if (root == null || k == 0) return;
getKLarge(root.right, k);
k--;
print(root.data);
getKLarge(root.left, k);
}

No comments:

Post a Comment