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.
Input: mat[][] = {{a,x,m,y},{b,g,d,j},{x,e,e,t},{r,a,k,s}}, word = "geeks" Output: 1 Explanation: The word "geeks" occur 1 time 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.
Mark current cell as visited (‘#’).
Explore all 4 directions recursively.
Sum all valid paths.
Restore original value (backtrack).
Return total count.
C++
#include<bits/stdc++.h>usingnamespacestd;intdfs(vector<vector<char>>&mat,stringword,introw,intcol,intidx){intn=mat.size();intm=mat[0].size();// Out of boundsif(row<0||row>=n||col<0||col>=m)return0;// Character mismatchif(mat[row][col]!=word[idx])return0;// Complete word foundif(idx==word.size()-1)return1;charch=mat[row][col];// Mark as visitedmat[row][col]='#';intcount=0;count+=dfs(mat,word,row+1,col,idx+1);count+=dfs(mat,word,row-1,col,idx+1);count+=dfs(mat,word,row,col+1,idx+1);count+=dfs(mat,word,row,col-1,idx+1);// Backtrackmat[row][col]=ch;returncount;}intcountOccurrence(vector<vector<char>>&mat,stringword){intn=mat.size();intm=mat[0].size();intres=0;for(inti=0;i<n;i++){for(intj=0;j<m;j++){res+=dfs(mat,word,i,j,0);}}returnres;}intmain(){vector<vector<char>>mat={{'S','N','B','S','N'},{'B','A','K','E','A'},{'B','K','B','B','K'},{'S','E','B','S','E'}};stringword="SNAKES";cout<<countOccurrence(mat,word)<<endl;return0;}
Java
classGFG{publicstaticintdfs(char[][]mat,Stringword,introw,intcol,intidx){intn=mat.length;intm=mat[0].length;// Out of boundsif(row<0||row>=n||col<0||col>=m)return0;// Character mismatchif(mat[row][col]!=word.charAt(idx))return0;// Complete word foundif(idx==word.length()-1)return1;charch=mat[row][col];// Mark as visitedmat[row][col]='#';intcount=0;// Explore all 4 directionscount+=dfs(mat,word,row+1,col,idx+1);count+=dfs(mat,word,row-1,col,idx+1);count+=dfs(mat,word,row,col+1,idx+1);count+=dfs(mat,word,row,col-1,idx+1);// Backtrackmat[row][col]=ch;returncount;}publicstaticintcountOccurrence(char[][]mat,Stringword){intres=0;for(inti=0;i<mat.length;i++){for(intj=0;j<mat[0].length;j++){res+=dfs(mat,word,i,j,0);}}returnres;}publicstaticvoidmain(String[]args){char[][]mat={{'S','N','B','S','N'},{'B','A','K','E','A'},{'B','K','B','B','K'},{'S','E','B','S','E'}};Stringword="SNAKES";System.out.println(countOccurrence(mat,word));}}
Python
defdfs(mat,word,row,col,idx):n=len(mat)m=len(mat[0])# Out of boundsifrow<0orrow>=norcol<0orcol>=m:return0# Character mismatchifmat[row][col]!=word[idx]:return0# Complete word foundifidx==len(word)-1:return1ch=mat[row][col]# Mark as visitedmat[row][col]='#'count=0count+=dfs(mat,word,row+1,col,idx+1)count+=dfs(mat,word,row-1,col,idx+1)count+=dfs(mat,word,row,col+1,idx+1)count+=dfs(mat,word,row,col-1,idx+1)# Backtrackmat[row][col]=chreturncountdefcountOccurrence(mat,word):res=0foriinrange(len(mat)):forjinrange(len(mat[0])):res+=dfs(mat,word,i,j,0)returnresif__name__=="__main__":mat=[['S','N','B','S','N'],['B','A','K','E','A'],['B','K','B','B','K'],['S','E','B','S','E']]word="SNAKES"print(countOccurrence(mat,word))
C#
usingSystem;classGFG{publicstaticintdfs(char[,]mat,stringword,introw,intcol,intidx){intn=mat.GetLength(0);intm=mat.GetLength(1);// Out of boundsif(row<0||row>=n||col<0||col>=m)return0;// Character mismatchif(mat[row,col]!=word[idx])return0;// Complete word foundif(idx==word.Length-1)return1;charch=mat[row,col];// Mark as visitedmat[row,col]='#';intcount=0;// Explore all 4 directionscount+=dfs(mat,word,row+1,col,idx+1);count+=dfs(mat,word,row-1,col,idx+1);count+=dfs(mat,word,row,col+1,idx+1);count+=dfs(mat,word,row,col-1,idx+1);// Backtrackmat[row,col]=ch;returncount;}publicstaticintcountOccurrence(char[,]mat,stringword){intans=0;intn=mat.GetLength(0);intm=mat.GetLength(1);for(inti=0;i<n;i++){for(intj=0;j<m;j++){ans+=dfs(mat,word,i,j,0);}}returnans;}staticvoidMain(){char[,]mat={{'S','N','B','S','N'},{'B','A','K','E','A'},{'B','K','B','B','K'},{'S','E','B','S','E'}};stringword="SNAKES";Console.WriteLine(countOccurrence(mat,word));}}
JavaScript
functiondfs(mat,word,row,col,idx){letn=mat.length;letm=mat[0].length;// Out of boundsif(row<0||row>=n||col<0||col>=m)return0;// Character mismatchif(mat[row][col]!==word[idx])return0;// Complete word foundif(idx===word.length-1)return1;letch=mat[row][col];// Mark as visitedmat[row][col]='#';letcount=0;count+=dfs(mat,word,row+1,col,idx+1);count+=dfs(mat,word,row-1,col,idx+1);count+=dfs(mat,word,row,col+1,idx+1);count+=dfs(mat,word,row,col-1,idx+1);// Backtrackmat[row][col]=ch;returncount;}functioncountOccurrence(mat,word){letres=0;for(leti=0;i<mat.length;i++){for(letj=0;j<mat[0].length;j++){res+=dfs(mat,word,i,j,0);}}returnres;}// Driver codeletmat=[['S','N','B','S','N'],['B','A','K','E','A'],['B','K','B','B','K'],['S','E','B','S','E']];letword="SNAKES";console.log(countOccurrence(mat,word));