class Solution {
public boolean exist(char[][] board, String word) {
for (int i=0; i<board.length; i++) {
for (int j=0; j<board[0].length; j++) {
boolean found = searchWordDFS(board, i, j, 0, word, "#");
if (found) {
return true;
}
}
}
return false;
}
private boolean isCellFit(char[][] board, int i, int j, int wordPos, String word, String visited) {
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || wordPos >= word.length()) {
return false; // out of grid
}
int index = i * board[0].length + j;
if (visited.contains("#" + index + "#")) {
return false; // already been there
}
return board[i][j] == word.charAt(wordPos);
}
private boolean searchWordDFS(char[][] board, int i, int j, int wordPos, String word, String visited) {
// Este important de tinut visited ca String si nu ca List/alt obiect pentru a fi pasat prin valoare,
// nu prin referinta, astfel incat, la intoarcerea fara succes din recursivitate indecsii din matrice
// vizitati sa fie abandonati
if (isCellFit(board, i, j, wordPos, word, visited)) {
visited += (i * board[0].length + j) + "#";
if (wordPos == word.length() - 1) {
return true;
}
boolean found = searchWordDFS(board, i, j + 1, wordPos + 1, word, visited); // right
if (!found) {
found = searchWordDFS(board, i, j - 1, wordPos + 1, word, visited); // left
}
if (!found) {
found = searchWordDFS(board, i + 1, j, wordPos + 1, word, visited); // down
}
if (!found) {
found = searchWordDFS(board, i - 1, j, wordPos + 1, word, visited); // up
}
return found;
}
return false;
}
}