


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'.
In the only output line prints the number of occurrences of the given string in the grid.
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
In thie approach we try to traverse in all directions when we found a matching character.
Here is the algorithm :
PI[i] : The maximum length of suffix of string[1, i], which is also a proper prefix of the string.
Here, proper prefix means that we exclude the empty string and the string itself.
for(i=0; i<n; i++)
for(j=0; i+j<n && j<m; j++)
// All elements diagonally, starting from top to bottom
for(int j=1; j<m; j++)
for(i=0; i<n && j+i<m; j++)
// All elements diagonally, starting from left to bottom
for(int i=0; i<n; i++)
for(int j=0; i-j >= 0 && j < m; j++)
// All elements diagonally, starting from left to top
for(int j=1; j<m; j++)
for(int i=n-1; i >= 0 && j+(n-1)-i < m; i--)
// All elements diagonally, starting from bottom to top
Remember we have to check for the reverse directions as well! In order to do that, we simply apply the same algorithm to the reverse of the string.