Lexicographical Paths

You are given an n x n grid where each square contains a letter between A and Z. You must move from the upper-left square (0, 0) to the lower-right square (n-1, n-1), moving only right or down.

Your goal is to find the lexicographically minimal string you can construct along the path.

Example 1:

Input: n = 4 , grid = ['AACA', 'BABC', 'ABDA', 'AACA']

Output: AAABACA

Explanation:

We must move from (0,0) to (3,3) using only right or down moves.

Among all possible paths, the string with the smallest lexicographic order is:

A → A → A → B → A → C → A

Example 2:

Input:

n = 2 , grid = ['AB', 'CD']

Output: ABD

Explanation:

Possible paths:

A → B → D

String = "ABD"

A → C → D

String = "ACD"

Since "ABD" is lexicographically smaller than "ACD", the answer is:

ABD

Now Your Turn!

Pick the correct output for the given input

Input: n = 3 , grid = ['ABC', 'DEF', 'GHI']

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ n ≤ 3000

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
string minimalGridPath(int n, vector<string>& grid) {
// Write your code here
return "";
}
};
Test Case

Input:

Grid