VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-count-number-given-string-present-2d-character-array/

⇱ Count of number of given string in 2D character array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

👁 2056958317

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.

👁 frame_1

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.

Output
3
Comment
Article Tags: