Count of number of given string in 2D character array
Last Updated : 10 Jun, 2026
Given a 2D grid mat[][] of size n × m consisting of characters and a string word of length l, find the total number of occurrences of the word in the grid.
The word can be formed by moving to adjacent cells in four directions (up, down, left, right), and the path may bend at 90-degree turns.
Each cell can be used at most once in a single occurrence.
Examples:
Input: mat[][] = {{S,N,B,S,N},{B,A,K,E,A},{B,K,B,B,K},{S,E,B,S,E}}, word = "SNAKES" Output: 3 Explanation: The word "SNAKES" occurs 3 times in the matrix.
DFS + Backtracking - O(n × m × 4^l) Time and O(l) Space
The idea is to use DFS + Backtracking. Start DFS from every cell that matches the first character of the word and explore in four directions (up, down, left, right) to match the remaining characters. To avoid revisiting a cell in the same path, mark it as visited during recursion and unmark it after exploring all paths. Repeat this for all valid starting cells to count all occurrences.
Traverse each cell in the grid.
If the cell matches the first character of the word, start DFS.
In DFS return 0 if out of bounds or mismatch occurs.
Return 1 if the last character of the word is matched.