Count Occurrences Of Given Word In A Grid | Google & Paytm | 🔥Self Explanatory Comments🔥

439
Jul 14, 2024
Jul 14, 2024

Given a 2D array of characters, find the number of occurrences of a given search word. The word can be formed by moving up, down, left, right, and around 90-degree bends. You cannot reuse any cell while forming the word.

N = 4, M = 5, target = SNAKES, grid =
{{S,N,B,S,N},
{B,A,K,E,A},
{B,K,B,B,K},
{S,E,B,S,E}}
Output: 3

Note: Hey There! Just Take A Look At The Code And Comments Within It. You'll Get It.
Note: Time Complexity And Auxiliary Space Is Mentioned With The Code.
Note: If You Have Any Kind Of Doubt, Just Comment And I'll Be There For You.

Approach : Using Backtracking

class Solution {
    vector<vector<int>> directions = {{-1,0}, {1,0}, {0,-1}, {0,1}};
    int N, M, length;
    
    int backtrack(vector<vector<char>>& grid, string& s, int R, int C, int index) {
        if(R < 0 || C < 0 || R == N || C == M || grid[R][C] != s[index])
            return 0;
            
        if(index == length-1)
            return grid[R][C] == s[index];
            
        int count = 0;
        
        grid[R][C] = '1';
        
        for(auto& dir : directions) {
            int reachRow = R + dir[0];
            int reachCol = C + dir[1];
            count += backtrack(grid, s, reachRow, reachCol, index + 1);
        }
        
        grid[R][C] = s[index];
        
        return count;
    }
    
public:
    // O(S * 4^(N*M)) & O(N*M) : Where S let be the total number of start cells or could say when grid[R][C] matches s[0].
    int findOccurrence(vector<vector<char>>& grid, string& s) {
        N = grid.size(), M = grid[0].size(), length = s.size();
        
        int count = 0;
        
        for(int R = 0; R < N; ++R)
            for(int C = 0; C < M; ++C)
                if(grid[R][C] == s[0])
                    count += backtrack(grid, s, R, C, 0);
        
        return count;
    }
};

𝗨𝗣𝗩𝗢𝗧𝗘 𝗜𝗙 𝗬𝗢𝗨 𝗟𝗜𝗞𝗘 𝗧𝗛𝗘 𝗦𝗢𝗟𝗨𝗧𝗜𝗢𝗡 👍

Note: This solutions are created by myself :)

Comments (8)