Count occurences of a given word in a 2-d array | Practice | GeeksforGeeks

Find the number of occurrences of a given search word in  a 2d-Array of characters where the word can go up, down, left, right and around 90 degree bends.

Example 1:
Input: 
R = 4, C = 5
mat = {{S,N,B,S,N},
       {B,A,K,E,A},
       {B,K,B,B,K},
       {S,E,B,S,E}}
target = SNAKES
Output:
3
Explanation: 
S N B S N
B A K E A
B K B B K
S E B S E
Total occurrence of the word is 3
and denoted by color.

Example 2:
Input:
R = 3, C = 3 
mat = {{c,a,t},
       {a,t,c},
       {c,t,a}}
target = cat
Output:
5
Explanation: Same explanation
as first example.


Your task:
You don’t need to read input or print anything. Your task is to complete the function findOccurrence() which takes the mat contaning N*M 2-d array of character and target as input parameters and returns thethe number of occurrences of target.

Expected Time Complexity: O(R*C*22*len), Where len is length of target String.
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ len ≤ 15
1 ≤ R, C ≤ 50
0
ra98530441 month ago
class Solution{   int[] di={1,-1,0,0};   int[] dj={0,0,1,-1};   public int findOccurrence(char mat[][], String target)   {       // Write your code here       int count=0;       boolean[][] visited=new boolean[mat.length][mat[0].length];       for(int i=0;i<mat.length;i++)       {           for(int j=0;j<mat[0].length;j++)           {               if(mat[i][j]==target.charAt(0))               {                   // System.out.println(i+"-"+j+" "+findOccurrence(mat,i,j,target,0,visited));                   count+=findOccurrence(mat,i,j,target,0,visited);               }           }       }       return count;   }   int findOccurrence(char mat[][],int i,int j,String target,int k,boolean[][] visited)   {       if(k==target.length()-1)           return 1;       visited[i][j]=true;       int count=0;       for(int l=0;l<4;l++)       {           int newi=i+di[l];           int newj=j+dj[l];           if(newi>=0 && newi<mat.length && newj>=0 && newj<mat[0].length && mat[newi][newj]==target.charAt(k+1) && !visited[newi][newj])           {             count+=findOccurrence(mat,newi,newj,target,k+1,visited);           }       }       visited[i][j]=false;       return count;   }}
How to find the time complexity of this solution?
0
surajchauhan72472019731 month ago
Easy c++ colution
class Solution{   int count = 0;   void dfs(vector<vector<char>>&mat, vector<vector<int>>&visited,int row, int col, string tar, string str, int x,int i,int j)   {       if(i >=row || j>=col || i < 0 || j < 0 || visited[i][j] == 1 || mat[i][j] != tar[x])         return;         visited[i][j] = 1;         str += mat[i][j];         if(str == tar)         {             count++;             return;         }         if(i+1 < row && i+1 >=0 && j>=0 && j < col &&  visited[i+1][j] == 0 && mat[i+1][j] == tar[x+1]){         dfs(mat,visited,row,col,tar,str,x+1,i+1,j);         visited[i+1][j] = 0;         }           if(i-1 < row && i-1 >=0 && j>=0 && j < col &&  visited[i-1][j] == 0 && mat[i-1][j] == tar[x+1]){         dfs(mat,visited,row,col,tar,str,x+1,i-1,j);         visited[i-1][j] = 0;         }         if(i < row && i >=0 && j+1>=0 && j+1 < col &&  visited[i][j+1] == 0 && mat[i][j+1] == tar[x+1]){         dfs(mat,visited,row,col,tar,str,x+1,i,j+1);         visited[i][j+1] = 0;         }        if(i < row && i >=0 && j-1>=0 && j-1 < col &&  visited[i][j-1] == 0 && mat[i][j-1] == tar[x+1]){         dfs(mat,visited,row,col,tar,str,x+1,i,j-1);         visited[i][j-1] = 0;         }                             }   public:   int findOccurrence(vector<vector<char> > &mat, string target){       int row = mat.size();       int col = mat[0].size();       count = 0;    for(int i=0;i<row;i++)    {        for(int j=0;j<col;j++)        {            if(target[0] == mat[i][j])            {               vector<vector<int>>visited(row, vector<int>(col, 0));               string str = "";               dfs(mat,visited,row,col,target,str,0,i,j);            }        }    }    return count;   }};
+1
aloksinghbais022 months ago
C++ solution using dfs having time complexity as O(n*m*2^(2*|target|)) and space complexity as O(N*M) is as follows :- 
 
Execution Time :- 0.6 / 3.2 sec
 
bool isValid(int x,int y,int n,int m,vector<vector<char>> &mat,vector<vector<bool>> &vis,char ch){       if(x < 0 || x >= n || y < 0 || y >= m) return (false);       if(vis[x][y] || mat[x][y] != ch) return (false);       return (true);   }      void dfs(int x,int y,int n,int m,vector<vector<char>> &mat,vector<vector<bool>> &vis,string &target,int i,int &cnt){       if(i == target.length()){           cnt++;           return;       }              int dx[] = {-1,0,1,0};       int dy[] = {0,1,0,-1};              for(int j = 0; j < 4; j++){           int nx = x + dx[j];           int ny = y + dy[j];           if(isValid(nx,ny,n,m,mat,vis,target[i])){               vis[nx][ny] = true;               dfs(nx,ny,n,m,mat,vis,target,i+1,cnt);               vis[nx][ny] = false;           }       }   }      int findOccurrence(vector<vector<char> > &mat, string target){       int n = mat.size(), m = mat[0].size();       int ans = 0;       for(int i = 0; i < n; i++){           for(int j = 0; j < m; j++){               if(mat[i][j] == target[0]){                   vector<vector<bool>> vis(n,vector<bool>(m,false));                   int cnt = 0;                   vis[i][j] = true;                   dfs(i,j,n,m,mat,vis,target,1,cnt);                   ans += cnt;               }           }       }       return (ans);   }
0
haritasboy12053 months ago
 C++ Solution:  
     int helper(string target,int i,int j,vector<vector<char> > &mat, int row,int col,int idx)
   {
       int count = 0;
       if(i >= 0 && i <= row && j >= 0 && j <= col && target[idx] == mat[i][j])
       {
           char temp = target[idx];
           idx += 1;
           
           mat[i][j] = 0;
           if(target[idx] == 0)
               count = 1;
           else
           {
               count += helper(target,i,j+1,mat,row,col,idx);
               count += helper(target,i,j-1,mat,row,col,idx);
               count += helper(target,i+1,j,mat,row,col,idx);
               count += helper(target,i-1,j,mat,row,col,idx);
           }
           
           mat[i][j] = temp;
       }
       return count;
   }
   int findOccurrence(vector<vector<char> > &mat, string target){
       int count = 0;
       for(int i=0;i<mat.size();i++)
       {
           for(int j=0;j<mat[0].size();j++)
           {
               count += helper(target,i,j,mat,mat.size()-1,mat[0].size()-1,0);
           }
       }
       return count;
   }
0
ramanshusingh19997 months ago
Solution below (C++):
class Solution{
   public:
   int search(string target, int r, int c, vector<vector<char> > &mat, int row_max, int col_max, int idx)
   {
       int found = 0;
    
       if (r >= 0 && r <= row_max && c >= 0 && c <= col_max && target[idx] == mat[r][c])
       {
           char temp = target[idx];
           idx += 1;
    
           mat[r][c] = 0;
    
           if (target[idx] == 0)
           {
               found = 1;
           }
           else
           {
               found += search(target, r, c + 1, mat, row_max, col_max, idx);
               found += search(target, r, c - 1, mat, row_max, col_max, idx);
               found += search(target, r + 1, c, mat, row_max, col_max, idx);
               found += search(target, r - 1, c, mat, row_max, col_max, idx);
           }
           mat[r][c] = temp;
       }
       return found;
   }
   int findOccurrence(vector<vector<char> > &mat, string target){
       int found = 0, i, j;
       for(i = 0; i < mat.size(); i++)
       {
           for(j = 0; j < mat[0].size(); j++)
           {
               found += search(target, i, j, mat, mat.size() - 1, mat[0].size() - 1, 0);
           }
       }
       return found;
   }
};
-1
itsmohitmk997 months ago
Exception in thread "main" java.lang.NullPointerException at java.base/java.util.StringTokenizer.<init>(StringTokenizer.java:199) at java.base/java.util.StringTokenizer.<init>(StringTokenizer.java:236) at GFG$FastReader.next(File.java:19) at GFG.main(File.java:53)
 
sc.nextLine() is to be removed from input
0
segerrlonewolf7 months ago
Receiving this exception while submission, something screwed in the input console for this problem
Exception in thread "main" java.lang.NumberFormatException: For input string: "n" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770) at GFG$FastReader.nextInt(File.java:31) at GFG.main(File.java:42)
0
Rishabh Singh7 months ago
Rishabh Singh
Can anyone tell me why my code is giving wrong answerclass Solution{    public:    int solve(int i,int j,int R,int C,vector<vector<char> > &matrix,string target,int index)    {        int found=0;        if(i>=0&&j>=0&&i<r&&j<c&&target[index]==matrix[i][j]) {="" char="" temp="target[index];" index++;="" matrix[i][j]="0;" if(index="=target.length())" return="" 1;="" else="" {="" found+="solve(i-1,j,R,C,matrix,target,index);" found+="solve(i+1,j,R,C,matrix,target,index);" found+="solve(i,j-1,R,C,matrix,target,index);" found+="solve(i,j+1,R,C,matrix,target,index);" }="" matrix[i][j]="temp;" }="" return="" found;="" }="" int="" findoccurrence(vector<vector<char=""> > &matrix, string target){        int R=matrix.size();        int C=matrix[0].size();        int ans=0;        for(int i=0;i<r;i++) {="" for(int="" j="0;j&lt;C;j++)" {="" ans+="solve(i,j,R,C,matrix,target,0);" }="" }="" return="" ans;="" }="" };="">
0
Devang8 months ago
Devang
C++ using lambdas
class Solution {    public:    const int d[5] = {0, -1, 0, 1, 0};    int findOccurrence(vector<vector<char> > &grid, string target) {        int m = grid.size(), n = grid[0].size();                int count = 0;        function<int(int, int,="" int)=""> dfs = [&](int i, int j, int idx) {            if( i < 0 or j < 0 or i >= m or j >= n or grid[i][j] != target[idx] ) return 0;            int count = 0;            if(idx == target.size() - 1) return 1;            char ch = grid[i][j];            grid[i][j] = '#';            for(int k = 0; k < 4; k++) {                int ni = i + d[k], nj = j + d[k+1];                count += dfs( ni, nj, idx + 1 );            }            grid[i][j] = ch;            return count;        };                for(int i = 0; i < m; i++)            for(int j = 0; j < n; j++)                count += dfs(i, j, 0);        return count;    }};
0
dhruv amin9 months ago
dhruv amin
Why can't we use DP here?dp[row][col][index]?
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.