Given an M × N matrix of characters, find all occurrences of a given string in the matrix. We are allowed to search the string in all eight possible directions, i.e., North, West, South, East, North-East, North-West, South-East, South-West. Note that there should not be any cycles in the output path.

For example, consider the following matrix of characters,

 [ D  E  M  X  B ]
 [ A  O  E  P  E ]
 [ D  D  C  O  D ]
 [ E  B  E  D  S ]
 [ C  P  Y  E  N ]

If the given string is CODE, following are all its occurrences in the matrix:

C(2, 2)   O(1, 1)   D(0, 0)   E(0, 1)
C(2, 2)   O(1, 1)   D(2, 0)   E(3, 0)
C(2, 2)   O(1, 1)   D(2, 1)   E(1, 2)
C(2, 2)   O(1, 1)   D(2, 1)   E(3, 0)
C(2, 2)   O(1, 1)   D(2, 1)   E(3, 2)
C(2, 2)   O(2, 3)   D(2, 4)   E(1, 4)
C(2, 2)   O(2, 3)   D(3, 3)   E(3, 2)
C(2, 2)   O(2, 3)   D(3, 3)   E(4, 3)

Practice this problem

We can use Depth–first search (DFS) to solve this problem. The idea is to start from each cell in the matrix and explore all eight paths possible and recursively check if they will lead to the solution or not. To make sure that the path is simple and doesn’t contain any cycles, keep track of cells involved in the current path in a matrix, and before exploring any cell, ignore the cell if it is already covered in the current path.

 
We can find all the possible locations we can move to from the given location by using the array that stores the relative position of movement from any location. For example, if the current location is (x, y), we can move to (x + row[k], y + col[k]) for 0 <= k <= 7 using the following array:

int row[] = { -1, -1, -1, 0, 0, 1, 1, 1 }
int col[] = { -1, 0, 1, -1, 1, -1, 0, 1 }
 
So, from position (x, y), we can move to:
 
(x – 1, y – 1)
(x – 1, y)
(x – 1, y + 1)
(x, y – 1)
(x, y + 1)
(x + 1, y – 1)
(x + 1, y)
(x + 1, y + 1)

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:

[(2, 2), (1, 1), (0, 0), (0, 1)]
[(2, 2), (1, 1), (2, 0), (3, 0)]
[(2, 2), (1, 1), (2, 1), (1, 2)]
[(2, 2), (1, 1), (2, 1), (3, 0)]
[(2, 2), (1, 1), (2, 1), (3, 2)]
[(2, 2), (2, 3), (2, 4), (1, 4)]
[(2, 2), (2, 3), (3, 3), (3, 2)]
[(2, 2), (2, 3), (3, 3), (4, 3)]

The time complexity of the proposed solution is exponential and requires additional space for the recursion (call stack).