Related Articles

# Find all occurrences of a given word in a matrix

• Difficulty Level : Hard
• Last Updated : 11 Jun, 2021

Given a 2D grid of characters and a word, find all occurrences of given word in grid. A word can be matched in all 8 directions at any point. Word is said be found in a direction if all characters match in this direction (not in zig-zag form).
The solution should print all coordinates if a cycle is found. i.e.
The 8 directions are, Horizontally Left, Horizontally Right, Vertically Up, Vertically Down and 4 Diagonals.

```Input:
mat[ROW][COL]= { {'B', 'N', 'E', 'Y', 'S'},
{'H', 'E', 'D', 'E', 'S'},
{'S', 'G', 'N', 'D', 'E'}
};
Word = “DES”
Output:
D(1, 2) E(1, 1) S(2, 0)
D(1, 2) E(1, 3) S(0, 4)
D(1, 2) E(1, 3) S(1, 4)
D(2, 3) E(1, 3) S(0, 4)
D(2, 3) E(1, 3) S(1, 4)
D(2, 3) E(2, 4) S(1, 4)

Input:
char mat[ROW][COL] = { {'B', 'N', 'E', 'Y', 'S'},
{'H', 'E', 'D', 'E', 'S'},
{'S', 'G', 'N', 'D', 'E'}};
char word[] ="BNEGSHBN";
Output:
B(0, 0) N(0, 1) E(1, 1) G(2, 1) S(2, 0) H(1, 0)
B(0, 0) N(0, 1) ```

We strongly recommend you to minimize your browser and try this yourself first.
This is mainly an extension of this post. Here with locations path is also printed.
The problem can be easily solved by applying DFS() on each occurrence of first character of the word in the matrix. A cell in 2D matrix can be connected to 8 neighbours. So, unlike standard DFS(), where we recursively call for all adjacent vertices, here we can recursive call for 8 neighbours only.

## CPP

 `// Program to find all occurrences of the word in``// a matrix``#include ``using` `namespace` `std;` `#define ROW 3``#define COL 5` `// check whether given cell (row, col) is a valid``// cell or not.``bool` `isvalid(``int` `row, ``int` `col, ``int` `prevRow, ``int` `prevCol)``{``    ``// return true if row number and column number``    ``// is in range``    ``return` `(row >= 0) && (row < ROW) &&``           ``(col >= 0) && (col < COL) &&``           ``!(row== prevRow && col == prevCol);``}` `// These arrays are used to get row and column``// numbers of 8 neighboursof a given cell``int` `rowNum[] = {-1, -1, -1, 0, 0, 1, 1, 1};``int` `colNum[] = {-1, 0, 1, -1, 1, -1, 0, 1};` `// A utility function to do DFS for a 2D boolean``// matrix. It only considers the 8 neighbours as``// adjacent vertices``void` `DFS(``char` `mat[][COL], ``int` `row, ``int` `col,``         ``int` `prevRow, ``int` `prevCol, ``char``* word,``         ``string path, ``int` `index, ``int` `n)``{``    ``// return if current character doesn't match with``    ``// the next character in the word``    ``if` `(index > n || mat[row][col] != word[index])``        ``return``;` `    ``//append current character position to path``    ``path += string(1, word[index]) + ``"("` `+ to_string(row)``            ``+ ``", "` `+ to_string(col) + ``") "``;` `    ``// current character matches with the last character``    ``// in the word``    ``if` `(index == n)``    ``{``        ``cout << path << endl;``        ``return``;``    ``}` `    ``// Recur for all connected neighbours``    ``for` `(``int` `k = 0; k < 8; ++k)``        ``if` `(isvalid(row + rowNum[k], col + colNum[k],``                    ``prevRow, prevCol))` `            ``DFS(mat, row + rowNum[k], col + colNum[k],``                ``row, col, word, path, index+1, n);``}` `// The main function to find all occurrences of the``// word in a matrix``void` `findWords(``char` `mat[][COL], ``char``* word, ``int` `n)``{``    ``// traverse through the all cells of given matrix``    ``for` `(``int` `i = 0; i < ROW; ++i)``        ``for` `(``int` `j = 0; j < COL; ++j)` `            ``// occurrence of first character in matrix``            ``if` `(mat[i][j] == word[0])` `                ``// check and print if path exists``                ``DFS(mat, i, j, -1, -1, word, ``""``, 0, n);``}` `// Driver program to test above function``int` `main()``{``    ``char` `mat[ROW][COL]= { {``'B'``, ``'N'``, ``'E'``, ``'Y'``, ``'S'``},``                          ``{``'H'``, ``'E'``, ``'D'``, ``'E'``, ``'S'``},``                          ``{``'S'``, ``'G'``, ``'N'``, ``'D'``, ``'E'``}``                        ``};` `    ``char` `word[] =``"DES"``;` `    ``findWords(mat, word, ``strlen``(word) - 1);` `    ``return` `0;``}`

## Java

 `// Java Program to find all occurrences of the word in``// a matrix``import` `java.util.*;` `class` `GFG``{` `static` `final` `int` `ROW = ``3``;``static` `final` `int` `COL = ``5``;` `// check whether given cell (row, col) is a valid``// cell or not.``static` `boolean` `isvalid(``int` `row, ``int` `col, ``int` `prevRow, ``int` `prevCol)``{``    ``// return true if row number and column number``    ``// is in range``    ``return` `(row >= ``0``) && (row < ROW) &&``        ``(col >= ``0``) && (col < COL) &&``        ``!(row == prevRow && col == prevCol);``}` `// These arrays are used to get row and column``// numbers of 8 neighboursof a given cell``static` `int` `rowNum[] = {-``1``, -``1``, -``1``, ``0``, ``0``, ``1``, ``1``, ``1``};``static` `int` `colNum[] = {-``1``, ``0``, ``1``, -``1``, ``1``, -``1``, ``0``, ``1``};` `// A utility function to do DFS for a 2D boolean``// matrix. It only considers the 8 neighbours as``// adjacent vertices``static` `void` `DFS(``char` `mat[][], ``int` `row, ``int` `col,``        ``int` `prevRow, ``int` `prevCol, ``char``[] word,``        ``String path, ``int` `index, ``int` `n)``{``    ``// return if current character doesn't match with``    ``// the next character in the word``    ``if` `(index > n || mat[row][col] != word[index])``        ``return``;` `    ``// append current character position to path``    ``path += (word[index]) + ``"("` `+ String.valueOf(row)``            ``+ ``", "` `+ String.valueOf(col) + ``") "``;` `    ``// current character matches with the last character``    ``// in the word``    ``if` `(index == n)``    ``{``        ``System.out.print(path +``"\n"``);``        ``return``;``    ``}` `    ``// Recur for all connected neighbours``    ``for` `(``int` `k = ``0``; k < ``8``; ++k)``        ``if` `(isvalid(row + rowNum[k], col + colNum[k],``                    ``prevRow, prevCol))` `            ``DFS(mat, row + rowNum[k], col + colNum[k],``                ``row, col, word, path, index + ``1``, n);``}` `// The main function to find all occurrences of the``// word in a matrix``static` `void` `findWords(``char` `mat[][], ``char` `[]word, ``int` `n)``{``    ``// traverse through the all cells of given matrix``    ``for` `(``int` `i = ``0``; i < ROW; ++i)``        ``for` `(``int` `j = ``0``; j < COL; ++j)` `            ``// occurrence of first character in matrix``            ``if` `(mat[i][j] == word[``0``])` `                ``// check and print if path exists``                ``DFS(mat, i, j, -``1``, -``1``, word, ``""``, ``0``, n);``}` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``char` `mat[][]= { {``'B'``, ``'N'``, ``'E'``, ``'Y'``, ``'S'``},``                    ``{``'H'``, ``'E'``, ``'D'``, ``'E'``, ``'S'``},``                    ``{``'S'``, ``'G'``, ``'N'``, ``'D'``, ``'E'``}};` `    ``char` `[]word =``"DES"``.toCharArray();` `    ``findWords(mat, word, word.length - ``1``);``}``}` `// This code is contributed by PrinciRaj1992`

## Python3

 `# Python3 Program to find all occurrences of the word in``# a matrix``ROW ``=` `3``COL ``=` `5` `# check whether given cell (row, col) is a valid``# cell or not.``def` `isvalid(row, col, prevRow, prevCol):``    ` `    ``# return true if row number and column number``    ``# is in range``    ``return` `(row >``=` `0``) ``and` `(row < ROW) ``and` `(col >``=` `0``) ``and` `\``           ``(col < COL) ``and` `not` `(row``=``=` `prevRow ``and` `col ``=``=` `prevCol)` `# These arrays are used to get row and column``# numbers of 8 neighboursof a given cell``rowNum ``=` `[``-``1``, ``-``1``, ``-``1``, ``0``, ``0``, ``1``, ``1``, ``1``]``colNum ``=` `[``-``1``, ``0``, ``1``, ``-``1``, ``1``, ``-``1``, ``0``, ``1``]` `# A utility function to do DFS for a 2D boolean``# matrix. It only considers the 8 neighbours as``# adjacent vertices``def` `DFS(mat, row, col,prevRow, prevCol, word,path, index, n):``    ` `    ``# return if current character doesn't match with``    ``# the next character in the word``    ``if` `(index > n ``or` `mat[row][col] !``=` `word[index]):``        ``return``    ` `    ``# append current character position to path``    ``path ``+``=` `word[index] ``+` `"("` `+` `str``(row)``+` `", "` `+` `str``(col) ``+` `") "``    ` `    ``# current character matches with the last character\``    ``# in the word``    ``if` `(index ``=``=` `n):``        ``print``(path)``        ``return``    ` `    ``# Recur for all connected neighbours``    ``for` `k ``in` `range``(``8``):``        ``if` `(isvalid(row ``+` `rowNum[k], col ``+` `colNum[k],prevRow, prevCol)):``            ``DFS(mat, row ``+` `rowNum[k], col ``+` `colNum[k],row, col, word, path, index ``+` `1``, n)` `# The main function to find all occurrences of the``# word in a matrix``def` `findWords(mat,word, n):``    ` `    ``# traverse through the all cells of given matrix``    ``for` `i ``in` `range``(ROW):``        ``for` `j ``in` `range``(COL):``            ` `            ``# occurrence of first character in matrix``            ``if` `(mat[i][j] ``=``=` `word[``0``]):``                ``# check and prif path exists``                ``DFS(mat, i, j, ``-``1``, ``-``1``, word, "", ``0``, n)` `# Driver code``mat ``=` `[[``'B'``, ``'N'``, ``'E'``, ``'Y'``, ``'S'``],``        ``[``'H'``, ``'E'``, ``'D'``, ``'E'``, ``'S'``],``        ``[``'S'``, ``'G'``, ``'N'``, ``'D'``, ``'E'``]]``word ``=` `list``(``"DES"``)``findWords(mat, word, ``len``(word) ``-` `1``)``    ` `# This code is contributed by SHUBHAMSINGH10`

## C#

 `// C# Program to find all occurrences of the word in``// a matrix``using` `System;` `class` `GFG``{` `static` `readonly` `int` `ROW = 3;``static` `readonly` `int` `COL = 5;` `// check whether given cell (row, col) is a valid``// cell or not.``static` `bool` `isvalid(``int` `row, ``int` `col, ``int` `prevRow, ``int` `prevCol)``{``    ``// return true if row number and column number``    ``// is in range``    ``return` `(row >= 0) && (row < ROW) &&``        ``(col >= 0) && (col < COL) &&``        ``!(row == prevRow && col == prevCol);``}` `// These arrays are used to get row and column``// numbers of 8 neighboursof a given cell``static` `int` `[]rowNum = {-1, -1, -1, 0, 0, 1, 1, 1};``static` `int` `[]colNum = {-1, 0, 1, -1, 1, -1, 0, 1};` `// A utility function to do DFS for a 2D bool``// matrix. It only considers the 8 neighbours as``// adjacent vertices``static` `void` `DFS(``char` `[,]mat, ``int` `row, ``int` `col,``        ``int` `prevRow, ``int` `prevCol, ``char``[] word,``        ``String path, ``int` `index, ``int` `n)``{``    ``// return if current character doesn't match with``    ``// the next character in the word``    ``if` `(index > n || mat[row,col] != word[index])``        ``return``;` `    ``// append current character position to path``    ``path += (word[index]) + ``"("` `+ String.Join(``""``,row)``            ``+ ``", "` `+ String.Join(``""``,col) + ``") "``;` `    ``// current character matches with the last character``    ``// in the word``    ``if` `(index == n)``    ``{``        ``Console.Write(path +``"\n"``);``        ``return``;``    ``}` `    ``// Recur for all connected neighbours``    ``for` `(``int` `k = 0; k < 8; ++k)``        ``if` `(isvalid(row + rowNum[k], col + colNum[k],``                    ``prevRow, prevCol))` `            ``DFS(mat, row + rowNum[k], col + colNum[k],``                ``row, col, word, path, index + 1, n);``}` `// The main function to find all occurrences of the``// word in a matrix``static` `void` `findWords(``char` `[,]mat, ``char` `[]word, ``int` `n)``{``    ``// traverse through the all cells of given matrix``    ``for` `(``int` `i = 0; i < ROW; ++i)``        ``for` `(``int` `j = 0; j < COL; ++j)` `            ``// occurrence of first character in matrix``            ``if` `(mat[i,j] == word[0])` `                ``// check and print if path exists``                ``DFS(mat, i, j, -1, -1, word, ``""``, 0, n);``}` `// Driver code``public` `static` `void` `Main(String[] args)``{``    ``char` `[,]mat= { {``'B'``, ``'N'``, ``'E'``, ``'Y'``, ``'S'``},``                    ``{``'H'``, ``'E'``, ``'D'``, ``'E'``, ``'S'``},``                    ``{``'S'``, ``'G'``, ``'N'``, ``'D'``, ``'E'``}};` `    ``char` `[]word =``"DES"``.ToCharArray();` `    ``findWords(mat, word, word.Length - 1);``}``}` `// This code is contributed by 29AjayKumar`

## Javascript

 ``

Output :

```D(1, 2) E(1, 1) S(2, 0)
D(1, 2) E(1, 3) S(0, 4)
D(1, 2) E(1, 3) S(1, 4)
D(2, 3) E(1, 3) S(0, 4)
D(2, 3) E(1, 3) S(1, 4)
D(2, 3) E(2, 4) S(1, 4) ```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up