[LeetCode] Match Alphanumerical Pattern in Matrix I

3078. Match Alphanumerical Pattern in Matrix I

You are given a 2D integer matrix board and a 2D character matrix pattern. Where 0 <= board[r][c] <= 9 and each element of pattern is either a digit or a lowercase English letter.

Your task is to find a submatrix of board that matches pattern.

An integer matrix part matches pattern if we can replace cells containing letters in pattern 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.

  • If pattern[r][c] is a digit, then part[r][c] must be the same digit.

  • If

1
pattern[r][c]

is a letter

1
x

:

  • For every pattern[i][j] == x, part[i][j] must be the same as part[r][c].
  • For every pattern[i][j] != x, part[i][j] must be different than part[r][c].

Return an array of length 2 containing the row number and column number of the upper-left corner of a submatrix of board which matches pattern. 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].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
bool match(vector<vector<int>>& A, vector<string>& P, int y, int x) {
unordered_map<char, int> vis;
unordered_map<int, char> rvis;
for(int i = 0; i < P.size(); i++) {
for(int j = 0; j < P[0].size(); j++) {
if(isdigit(P[i][j])) {
if(A[i+y][j+x] != P[i][j] - '0') return false;
} else {
char ch = P[i][j];
int val = A[i+y][j+x];
if(vis.count(ch) and rvis.count(val)) {
if(vis[ch] != val or rvis[val] != ch) return false;
} else if(vis.count(ch) or rvis.count(val)) return false;
else {
vis[ch] = val;
rvis[val] = ch;
}
}
}
}
return true;
}
public:
vector<int> findPattern(vector<vector<int>>& board, vector<string>& pattern) {
for(int i = 0; i < board.size() - pattern.size() + 1; i++) for(int j = 0; j < board[0].size() - pattern[0].size() + 1; j++) {
if(match(board, pattern, i, j)) return {i,j};
}
return {-1,-1};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/04/10/PS/LeetCode/match-alphanumerical-pattern-in-matrix-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.