![]() |
VOOZH | about |
Given a 2D integer matrix mat[][] and a 2D character matrix pat[][]. Where 0 <= mat[r][c] <= 9 and each element of pat is either a digit or a lowercase English letter. The task is to find a submatrix of mat that matches pat. An integer matrix part matches pat if we can replace cells containing letters in pat with some digits (each distinct letter with a unique digit) in such a way that the resulting matrix becomes identical to the integer matrix part. In other words,
The matrices have identical dimensions.
Return an array of length 2 containing the row number and column number of the upper-left corner of a submatrix of mat which matches pat. If there is more than one such submatrix, return the coordinates of the submatrix with the lowest row index, and in case there is still a tie, return the coordinates of the submatrix with the lowest column index. If there are no suitable answers, return {-1, -1}.
Example:
Input: mat = {{1,2,2},{2,2,3},{2,3,3}}, pat = {"ab","bb"}
Output: {0,0}
Explanation: If we consider this mapping: "a" -> 1 and "b" -> 2; the submatrix with the upper-left corner (0,0) is a match as outlined in the matrix above.
Note that the submatrix with the upper-left corner (1,1) is also a match but since it comes after the other one, we return {0,0}.Input: mat = {{1,1,2},{3,3,4},{6,6,6}}, pat = {"ab","66"}
Output: {1,1}
Explanation: If we consider this mapping: "a" -> 3 and "b" -> 4; the submatrix with the upper-left corner (1,1) is a match as outlined in the matrix above.
Note that since the corresponding values of "a" and "b" must differ, the submatrix with the upper-left corner (1,0) is not a match. Hence, we return {1,1}.
Approach:
The main intuition here is that each distinct letter in the pat corresponds to a unique digit in the mat. This means we can think of the letters as placeholders for some digit. Our task is to find where in the mat we can match the structure of the pat, with each distinct letter mapping to a unique digit.
The approach is to iterate over each possible position in the mat that could be the upper-left corner of a matching submatrix. For each position, we check if we can map the letters in the pat to the digits in the mat such that the pat and the submatrix become identical. We use a map to store the current mappings of letters to digits, and a set to keep track of which digits are already used.
Steps-by-step approach:
Below is the implementation of the above approach:
Starting position of the pat: (0, 0)
Time complexity: O(m1 * n1 * m2 * n2), m1, n1, m2, n2 are the lenghs and widths of the mat and the pat.
Auxiliary Space: O(1)