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
Try It Yourself
redirect icon

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>
using namespace std;

int dfs(vector<vector<char>> &mat, string word, int row, int col, int idx) {

    int n = mat.size();
    int m = mat[0].size();

    // Out of bounds
    if (row < 0 || row >= n || col < 0 || col >= m) return 0;

    // Character mismatch
    if (mat[row][col] != word[idx]) return 0;

    // Complete word found
    if (idx == word.size() - 1) return 1;

    char ch = mat[row][col];

    // Mark as visited
    mat[row][col] = '#';

    int count = 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);

    // Backtrack
    mat[row][col] = ch;

    return count;
}

int countOccurrence(vector<vector<char>> &mat, string word) {

    int n = mat.size();
    int m = mat[0].size();

    int res = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            res += dfs(mat, word, i, j, 0);
        }
    }

    return res;
}

int main() {

    vector<vector<char>> mat = {
        {'S','N','B','S','N'},
        {'B','A','K','E','A'},
        {'B','K','B','B','K'},
        {'S','E','B','S','E'}
    };

    string word = "SNAKES";

    cout << countOccurrence(mat, word) << endl;

    return 0;
}
Java
class GFG {

    public static int dfs(char[][] mat, String word, int row, int col, int idx) {

        int n = mat.length;
        int m = mat[0].length;

        // Out of bounds
        if (row < 0 || row >= n || col < 0 || col >= m) return 0;

        // Character mismatch
        if (mat[row][col] != word.charAt(idx)) return 0;

        // Complete word found
        if (idx == word.length() - 1) return 1;

        char ch = mat[row][col];

        // Mark as visited
        mat[row][col] = '#';

        int count = 0;

        // Explore all 4 directions
        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);

        // Backtrack
        mat[row][col] = ch;

        return count;
    }

    public static int countOccurrence(char[][] mat, String word) {

        int res = 0;

        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                res += dfs(mat, word, i, j, 0);
            }
        }

        return res;
    }

    public static void main(String[] args) {

        char[][] mat = {
            {'S','N','B','S','N'},
            {'B','A','K','E','A'},
            {'B','K','B','B','K'},
            {'S','E','B','S','E'}
        };

        String word = "SNAKES";

        System.out.println(countOccurrence(mat, word));
    }
}
Python
def dfs(mat, word, row, col, idx):

    n = len(mat)
    m = len(mat[0])

    # Out of bounds
    if row < 0 or row >= n or col < 0 or col >= m:
        return 0

    # Character mismatch
    if mat[row][col] != word[idx]:
        return 0

    # Complete word found
    if idx == len(word) - 1:
        return 1

    ch = mat[row][col]

    # Mark as visited
    mat[row][col] = '#'

    count = 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)

    # Backtrack
    mat[row][col] = ch

    return count


def countOccurrence(mat, word):

    res = 0

    for i in range(len(mat)):
        for j in range(len(mat[0])):
            res += dfs(mat, word, i, j, 0)

    return res


if __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#
using System;

class GFG {

    public static int dfs(char[,] mat, string word, int row, int col, int idx) {

        int n = mat.GetLength(0);
        int m = mat.GetLength(1);

        // Out of bounds
        if (row < 0 || row >= n || col < 0 || col >= m) return 0;

        // Character mismatch
        if (mat[row, col] != word[idx]) return 0;

        // Complete word found
        if (idx == word.Length - 1) return 1;

        char ch = mat[row, col];

        // Mark as visited
        mat[row, col] = '#';

        int count = 0;

        // Explore all 4 directions
        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);

        // Backtrack
        mat[row, col] = ch;

        return count;
    }

    public static int countOccurrence(char[,] mat, string word) {

        int ans = 0;

        int n = mat.GetLength(0);
        int m = mat.GetLength(1);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                ans += dfs(mat, word, i, j, 0);
            }
        }

        return ans;
    }

    static void Main() {

        char[,] mat = {
            {'S','N','B','S','N'},
            {'B','A','K','E','A'},
            {'B','K','B','B','K'},
            {'S','E','B','S','E'}
        };

        string word = "SNAKES";

        Console.WriteLine(countOccurrence(mat, word));
    }
}
JavaScript
function dfs(mat, word, row, col, idx) {

    let n = mat.length;
    let m = mat[0].length;

    // Out of bounds
    if (row < 0 || row >= n || col < 0 || col >= m) return 0;

    // Character mismatch
    if (mat[row][col] !== word[idx]) return 0;

    // Complete word found
    if (idx === word.length - 1) return 1;

    let ch = mat[row][col];

    // Mark as visited
    mat[row][col] = '#';

    let count = 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);

    // Backtrack
    mat[row][col] = ch;

    return count;
}

function countOccurrence(mat, word) {

    let res = 0;

    for (let i = 0; i < mat.length; i++) {
        for (let j = 0; j < mat[0].length; j++) {
            res += dfs(mat, word, i, j, 0);
        }
    }

    return res;
}

// Driver code
let mat = [
    ['S','N','B','S','N'],
    ['B','A','K','E','A'],
    ['B','K','B','B','K'],
    ['S','E','B','S','E']
];

let word = "SNAKES";

console.log(countOccurrence(mat, word));

Output
3
Comment