Grid and phrase | Hackerearth practice problem solution

Problem:-

You are given an n*m grid which contains lower case English letters. How many times does the phrase “saba” appear horizontally, vertically, and diagonally in the grid?

Input format

• First line: Two integer n and m, where n denotes (1 <= n,m <= 100) the number of rows and m denotes the number of columns in the grid
• Next n lines: Each line must contain a string of length m which contains lower-case English letters only

Output format

Print the number of times the word “saba” appears in the grid.

Sample Input
`5 5saferamjadbabolaaronsongs`
Sample Output
`2`
Time Limit: 1
Memory Limit: 256
Source Limit:

Explanation

The phrase “saba” must look one of thease shapes :

 s a b a

 s a b a

 s a b a

 a b a s

$10$

Code:-

This solution is based on the c++ language and you can submit ib c++14 and c++17 also.

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
char s[n+1][m+1];
for(int i=0;i<n;i++)
cin>>s[i];
int ans=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(s[i][j]==‘s’)
{
// for checking in horizontal direction
if(j+3<m)
{
if(s[i][j]==‘s’ && s[i][j+1]==‘a’ && s[i][j+2]==‘b’ && s[i][j+3]==‘a’)
ans++;
// for checking in downward direction
if(i+3<n)
{
if(s[i][j]==‘s’ && s[i+1][j+1]==‘a’ && s[i+2][j+2]==‘b’ && s[i+3][j+3]==‘a’)
ans++;
}
}
// for checking in vertical direction
if(i+3<n)
{
if(s[i][j]==‘s’ && s[i+1][j]==‘a’ && s[i+2][j]==‘b’ && s[i+3][j]==‘a’)
ans++;
}
// for checking in upward diagonal
if((i3)>=0 && (j+3)<m)
{

if(s[i][j]==‘s’ && s[i1][j+1]==‘a’ && s[i2][j+2]==‘b’ && s[i3][j+3]==‘a’)
ans++;

}
}
}
}
// printing of ans
cout<<ans;
return 0;
}

Recommended Post:-

MCQs:-