A textile inspector is auditing a woven fabric sample for a specific dye motif. The fabric is represented as a grid of dyed threads: m rows (weft threads) by n columns (warp threads), where each cell holds one lowercase letter denoting a thread color. The inspector also has a target motif — a string of lowercase letters representing a sequence of thread colors.
A cell is horizontally woven if it lies within some contiguous run of cells in its row that reads exactly the motif from left to right. A cell is vertically woven if it lies within some contiguous run of cells in its column that reads exactly the motif from top to bottom. A cell is doubly woven if it is both horizontally woven and vertically woven — the horizontal run and the vertical run covering it do not need to share any particular starting position, and occurrences within the same row or column may overlap each other.
Count how many cells of the fabric are doubly woven.
Line 1: two integers m and n — the number of rows and columns of the fabric grid.
Lines 2 to m+1: m strings, each of length n, consisting of lowercase English letters — the fabric grid, row by row.
Line m+2: a string — the motif.
A single integer — the number of doubly woven cells.
a-z).Example 1
Input
3 3 aba bab aba ab
Expected
4
Explanation
The grid is row0="aba", row1="bab", row2="aba", with motif "ab". Horizontally: row0 has "ab" starting at column 0 (covers columns 0-1); row1 has "ab" starting at column 1 (covers columns 1-2); row2 has "ab" starting at column 0 (covers columns 0-1). Vertically: column 0 reads "aba" top-to-bottom, containing "ab" starting at row 0 (covers rows 0-1); column 1 reads "bab", containing "ab" starting at row 1 (covers rows 1-2); column 2 reads "aba", containing "ab" starting at row 0 (covers rows 0-1). Intersecting the horizontal and vertical coverage, the doubly woven cells are (row0,col0), (row1,col1), (row1,col2), and (row2,col1) — 4 cells.
Example 2
Input
2 2 ab cd xy
Expected
0
Explanation
The grid is "ab"/"cd" and the motif is "xy". Neither row contains "xy", and neither column (reading "ac" or "bd" top-to-bottom) contains "xy" either, so no cell is even horizontally woven. The answer is 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →