GeeksforGeeks » Algorithms

Google Interview Question

(5 posts)
  1. blunderboy
    Member
    Posted 1 year ago #

    You are given a n*n matrix.Every cell of the matrix contain some value (positive).
    You are currently standing at (0,0) and you have to go to right most and botom most cell ((n-1)*(n-1))
    You can move either right or down.

    Q1. Find the most optimal path.

    Q2. Find the second most optimal path.

    Q3. Find the kth most optimal path.

  2. abc
    guest
    Posted 1 year ago #

    We can easily use DP to find atleast the most optimal path.
    Say the given array is arr[n][n], let A[n][n] be the matrix we make in our DP solution where A[i][j] is the sum of all values we encounter in the path when we travel from arr[0][0] to arr[i][j]. Note that the path chosen is such that this sum is minimum.
    So A[i][j] = arr[i][j] + max (A[i][j-1], A[i-1][j]), based on the fact that we can reach i,j only from a cell on its left or top .
    Also we will have to pre-fill A[0][j] and A[i][0]
    Keep a backtrack pointer pointing to the cell previous in the path.

    Not very sure about the 2nd most optimal or rather kth most optimal way!

  3. abc
    guest
    Posted 1 year ago #

    A correction:

    A[i][j] = arr[i][j] + min (A[i][j-1], A[i-1][j]).
    Also we don't even need a backtrack pointer. We can backtrace recursively using the matrix A.
    Also if we write a function backtraceAll...then we can make a max heap of k nodes every time. each node has the value of that path and a pointer to the list containing all the nodes encountered in this path. So the root of the max heap will have the maximum value of path. for any new path if the pathValue > (value at root) discard, else make it the root and call heapify. at the end, root of maxheap will be the kth optimal path.
    For 2nd most optimal path we need not make a heap

  4. st0le
    guest
    Posted 1 year ago #

    This is fairly simple, look here http://mathschallenge.net/index.php?section=problems&show=true&titleid=random_routes&full=true

    the answer is (2n)! / (n! n!) and there is no second or kth optimal path, all paths will measure the same length ie = 2n

  5. nutcracker
    guest
    Posted 1 year ago #

    isn't this Dijkstra's algo?
    the second most optimal can be found by removing one link(i.e. making one entry as infinite on the shortest path) one by one and returning the least of all of them...


Reply

You must log in to post.

RSS feed for this topic