Problem
Given a m x n 2D board of characters and a word, find how many times the word is present in the board.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring.
Note: The same letter cell may not be used more than once.
Input Format
First line contains two space separated integers m, n that denotes the number of rows and columns in the board respectively. Next m lines contain n characters each. Last line contains the word to be searched.
Constraints
1 <= m, n <= 5
1 <= lengthOf(word) <= 30
enter code here
Output Format
Print the total count of the given word in the 2-D board.
Sample Input
3 4
HDST
ANEO
BENY
NEST // word
Sample Output
2
Also I am not able to satisfy the test case
5 5
LACOO
OOOCL
NLOOO
ECOCO
MECOO
COOLOOC
Output should be
28
My Code
public static void main(String[] args) {
int m, n;
Scanner sc = new Scanner(System.in);
m = sc.nextInt();
n = sc.nextInt();
char[][] board = new char[m][n + 1];
for (int i = 0; i < m; i++) {
String temp = sc.next();
board[i] = temp.toCharArray();
}
String word = sc.next();
System.out.print(new Result().countWord(board, word, m, n));
}
static class Result {
static boolean[][] visited;
static int count = 0;
int countWord(char board[][], String word, int m, int n) {
visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == word.charAt(0)) {
if(searchWord(board, word, i, j, m, n, 0))
count++;
}
}
}
return count;
}
static boolean searchWord(char board[][], String word, int i, int j, int m, int n, int index) {
if (index == word.length()) {
count++;
return true;
}
if (i < 0 || j < 0 || i >= m || j >= n)
return false;
if (visited[i][j] || board[i][j] != word.charAt(index))
return false;
visited[i][j] = true;
if (searchWord(board, word, i - 1, j, m, n, index + 1) ||
searchWord(board, word, i + 1, j, m, n, index + 1) ||
searchWord(board, word, i, j - 1, m, n, index + 1) ||
searchWord(board, word, i, j + 1, m, n, index + 1)) {
return true;
}
visited[i][j] = false;
return false;
}
}