Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

HackerEarth Grid and phrase problem solution

YASH PAL, 31 July 2024
In this HackerEarth Grid and phrase problem solution, 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?
HackerEarth Grid and phrase problem solution

HackerEarth Grid and phrase problem solution.

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int M=1e2+10;
char jad[M][M];
int n,m,ans;
bool check(char a,char b,char c,char d)
{
if(a=='s' && b=='a' && c=='b' && d=='a')
return true;
return false;
}
int32_t main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>jad[i][j];
for(int i=4;i<=n;i++)
for(int j=1;j<=m-3;j++)
if(check(jad[i][j],jad[i-1][j+1],jad[i-2][j+2],jad[i-3][j+3]))
ans++;
for(int i=1;i<=n-3;i++)
for(int j=1;j<=m-3;j++)
if(check(jad[i][j],jad[i+1][j+1],jad[i+2][j+2],jad[i+3][j+3]))
ans++;
for(int i=1;i<=n;i++)
for(int j=1;j<=m-3;j++)
if(check(jad[i][j],jad[i][j+1],jad[i][j+2],jad[i][j+3]))
ans++;
for(int i=1;i<=n-3;i++)
for(int j=1;j<=m;j++)
if(check(jad[i][j],jad[i+1][j],jad[i+2][j],jad[i+3][j]))
ans++;
cout<<ans<<endl;
return 0;
}

Second solution

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxN=1e3+123;

string saba="saba";
string s[maxN];

int32_t main(){
int n,m;
cin>>n>>m;
int ans=0;
for(int i=0;i<n;i++)cin>>s[i];
for(int i=0;i<n-3;i++){
for(int j=0;j<m-3;j++){
bool b=true;
for(int k=0;k<4;k++){
if(s[i+k][j+k]!=saba[k])b=false;
}
if(b)ans++;
}
}
for(int i=0;i<n-3;i++){
for(int j=0;j<m;j++){
bool b=true;
for(int k=0;k<4;k++){
if(s[i+k][j]!=saba[k])b=false;
}
if(b)ans++;
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m-3;j++){
bool b=true;
for(int k=0;k<4;k++){
if(s[i][j+k]!=saba[k])b=false;
}
if(b)ans++;
}
}
for(int i=3;i<n;i++){
for(int j=0;j<m-3;j++){
bool b=true;
for(int k=0;k<4;k++){
if(s[i-k][j+k]!=saba[k])b=false;
}
if(b)ans++;
}
}
cout<<ans<<endl;
}
coding problems

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes