Count of number of given string in 2D character array (original) (raw)

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.

**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.

#include <bits/stdc++.h> using namespace std;

int dfs(vector<vector> &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> &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));

`