


You are given a two-dimensional grid having 'N' rows and 'M' columns, consisting of upper case characters. You are also given a word 'WORD'. You have to find the number of occurrences of that word in the grid.
Starting from a given cell, a word can be formed by moving in all eight directions: horizontally left, horizontally right, vertically up, vertically down, and four diagonal directions.
Example :There are three occurrences of the word 'NINJA' in the following grid:

1) Given word will not be a single character.
2) If occurrences of the given word start from two different cells, then these two occurrences are considered to be different.
Consider the word 'XYX' to be searched in the string 'AXYXB'. Here, we find an occurrence of 'XYX' at index 2 going in the right direction, and another occurrence at index 4 going in the left direction.
Although these two words correspond to the same word, they will be considered as different occurrences.
The first input line contains two integers, 'N' and 'M', the number of rows and columns respectively.
The next 'N' input lines representing the rows of the grid, contain a string each of length 'M'.
The next input line contains a string 'WORD'.
Output Format :
In the only output line prints the number of occurrences of the given string in the grid.
Note :
You don't have to print anything. It has already been taken care of, just implement the given function.
1 <= N <= 10^3
1 <= M <= 10^3
1 <= N*M <= 10^6
2 <= WORD.size <= 10^3
Time Limit : 1 sec
5 5
AANIQ
PJINT
NINJA
BLJIJ
PRADN
NINJA
3

3 4
RIAN
IAIR
AIRI
AIR
5
From each cell, try moving in all 8 directions as long as the string matches.
In thie approach we try to traverse in all directions when we found a matching character.
Here is the algorithm :
O(N*M*X), where ‘N’ and ‘M’ are the number of rows and columns of the grid, and ‘X’ is the length of the given word.
There are N*M cells to consider, and for each cell, we go till a distance ‘X’ in the worst case for all eight directions. Hence, the overall time complexity will be O(N*M*X).
O(1)
We are not using any extra space. Hence, the overall space complexity will be O(1).