Deloitte | COGNIZANT | IBM | CAPGEMINI
import java.util.Scanner;
public class TestClass
{
static int countOccurrence(int n, String grid[], String word)
{
int count = 0;
int wordLen = word.length();
int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1};
int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1};
for (int r = 0; r < n; r++)
{
for (int c = 0; c < n; c++)
{
for (int dir = 0; dir < 8; dir++)
{
int k;
int currR = r;
int currC = c;
for (k = 0; k < wordLen; k++)
{
if (currR < 0 currR >= n currC < 0 || currC >= n)
{
break;
}
if (grid[currR].charAt(currC) != word.charAt(k))
{
break;
}
currR += dx[dir];
currC += dy[dir];
}
if (k == wordLen)
{
count++;
}
}
}
}
return count;
}
public static void main(String args[])
{
int n;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
sc.nextLine();
String grid[] = new String[n];
for(int i=0; i<n; i++)
{
grid[i] = sc.nextLine();
}
String word;
word = sc.nextLine();
System.out.println(countOccurrence(n,grid,word));
}
}
FLIPKART✅
q4✅
690 ·