09 ianuarie 2024

50 DSA-Questions: #14

#14. Word Search
Given an m x n grid of characters board and a string word, return true if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
public class Exercise14 {
private final String[][] BOARD = {{"A", "B", "C", "E"},{"S", "F", "C", "S"},{"A", "D", "E", "E"}}; // 1 <= m, n <= 6
// private final String WORD = "ABCCED"; // 1 <= length <= 15
// private final String WORD = "SEE";
private final String WORD = "ABCB";

private boolean isCellFit(int i, int j , int wordPos) {
if (i < 0 || i >= BOARD.length || j < 0 || j >= BOARD[0].length || wordPos >= WORD.length()) {
return false; // out of grid
}
if (BOARD[i][j].length() > 1) {
return false; // already been there
}
return BOARD[i][j].charAt(0) == WORD.charAt(wordPos);
}

private void resetBoard() {
for (int i=0; i<BOARD.length; i++) {
for (int j = 0; j < BOARD[0].length; j++) {
BOARD[i][j] = BOARD[i][j].charAt(0) + "";
}
}
}

private boolean searchWordDFS(int i, int j, int wordPos) {
if (isCellFit(i, j, wordPos)) {
if (wordPos == WORD.length() - 1) {
return true;
}
BOARD[i][j] += BOARD[i][j]; // mark as visited
boolean found = searchWordDFS(i, j + 1, wordPos + 1);
if (!found) {
found = searchWordDFS(i, j - 1, wordPos + 1);
}
if (!found) {
found = searchWordDFS(i + 1, j, wordPos + 1);
}
if (!found) {
found = searchWordDFS(i - 1, j, wordPos + 1);
}
return found;
}
return false;
}

private void solve() {
for (int i=0; i<BOARD.length; i++) {
for (int j=0; j<BOARD[0].length; j++) {
resetBoard();
boolean found = searchWordDFS(i, j, 0);
if (found) {
System.out.println("True");
return;
}
}
}
System.out.println("False");
}


public static void main(String args[]) {
new Exercise14().solve();
}
}

Niciun comentariu: