Kth path

4.5

2 votes
Hard, Algorithms, Approved
Problem

You have been given a N x M matrix containing lowercase English alphabets ('a' - 'z'). Consider path in which you can either move one unit right of current cell or move unit down of current cell i.e from (x,y) you can either move to (x+1,y) or move to (x,y+1).
Consider all the paths going from (1,1) to (N,M) in this matrix. Each such path can be described by sequence of labels ('a' - 'z') of all the cells visited on the way. There will be many such paths going from (1,1) to (N,M). You have to find out lexicographic Kth path in the matrix.

Lexicographic Kth path can be described as:
Take all the possible paths in a vector and sort them. Print the path at Kth position in the array.

INPUT:
First line will consist of two integers N and M. Next N lines will consist of M characters. Next line will consist of number K.

OUTPUT:
Output a string consisting of N+M1 letters denoting the lexicographic Kth path. If total number of paths in the matrix are less than K, print 1.

CONSTRAINTS:
1NM106
1K1018
All the characters in the matrix will be lowercase English alphabets ('a'-'z').

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

All the possible paths in this matrix are : ababd,abcbd,abcbd,abcdd,abcdd,abcdd. Thus Lexicographic 3rd path is abcbd.

Editor Image

?