Problem Description
Given a 2D integer matrix board and a 2D character matrix pattern, the task is to locate a submatrix in board that matches pattern. A match means that when digits in pattern remain the same, each letter in pattern can be mapped to a unique digit such that all occurrences of the same letter correspond to the same digit in the submatrix and different letters correspond to different digits. If the submatrix exists, return the coordinates [row, col] of its top-left corner; if multiple exist, choose the one with the smallest row, and then column. Otherwise, return [-1, -1].
Key Insights
- Iterate over every possible submatrix in board that has the same dimensions as pattern.
- For each candidate submatrix, maintain a mapping for letters to digits and a reverse mapping to enforce unique assignments.
- For pattern digits (characters that are digits), directly compare with the corresponding board value.
- For pattern letters, either assign a mapping (if not assigned) or check that the assigned digit matches, while ensuring that two distinct letters never map to the same digit.
- Due to constraints (board and pattern sizes up to 50), a brute-force approach is acceptable.
Space and Time Complexity
Time Complexity: O((n - p + 1) * (m - q + 1) * (p * q)), where n, m are the dimensions of board and p, q are the dimensions of pattern. Space Complexity: O(1) extra space (only maps for letter-digit assignments, with at most 26 entries).
Solution
The solution iterates over every valid top-left coordinate in board where a submatrix of pattern dimensions can be extracted. For each candidate submatrix, the algorithm checks if it matches the pattern using two hash tables: one for mapping letters to digits and another for mapping digits back to letters, ensuring each letter maps to a unique digit. If all cells satisfy the rule (digits compare exactly when a digit is specified, and letters abide by the unique mapping condition), the submatrix is valid and its coordinates are returned. If none is found, [-1, -1] is returned.