1093. Grid Pattern Hits
A textile designer scans a fabric swatch into a grid of thread codes, each a lowercase letter, and wants to find every place where a smaller motif appears. Given the character matrix grid and the smaller character matrix pattern, report every position where the motif fits exactly: the top-left corner (r, c) is a hit when grid[r + i][c + j] == pattern[i][j] for every valid i and j.
Return all hits as [r, c] pairs, sorted by r first and then by c. Occurrences may overlap, and the answer is an empty list when the motif never appears. The pattern is never taller or wider than the grid. Comparing the motif cell by cell at every corner is far too slow when both matrices are large.
Example 1
- Input:
- grid = [["a","b","a","b"],["b","a","b","a"],["a","b","a","b"]]pattern = [["a","b"],["b","a"]]
- Output:
- [[0,0],[0,2],[1,1]]
- Explanation:
The 2x2 motif fits with its corner at (0, 0), (0, 2) and (1, 1); the occurrences are allowed to overlap.
Example 2
- Input:
- grid = [["a","a","a","a"],["a","b","c","a"],["a","a","a","a"]]pattern = [["b","b"]]
- Output:
- []
- Explanation:
The motif
bbnever appears, so the result is an empty list.
Example 3
- Input:
- grid = [["q"]], pattern = [["q"]]
- Output:
- [[0,0]]
- Explanation:
A single-cell grid containing the motif has exactly one hit at the origin.
Constraints
1 ≤ grid.length, grid[0].length ≤ 400 (the grid is rectangular)
1 ≤ pattern.length ≤ grid.length and 1 ≤ pattern[0].length ≤ grid[0].length (the pattern is rectangular)
All characters are lowercase English letters
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 3,200 msC++ 800 msJava 1,600 msJavaScript 1,600 msTypeScript 1,600 ms
Expected complexity
- Time
- O(R * C)
- Space
- O(R * C)