public class WordSearch {
private static final int[][] DIRECTIONS = {{-1,0},{1,0},{0,-1},{0,1}};
public boolean exist(char[][] board, String word) {
int rows = board.length;
if (rows == 0) return false;
int cols = board[0].length;
boolean[][] visited = new boolean[rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (board[r][c] == word.charAt(0)) {
if (backtrack(board, word, 0, r, c, visited)) {
return true;
}
}
}
}
return false;
}
private boolean backtrack(char[][] board, String word, int index, int row, int col, boolean[][] visited) {
if (index == word.length()) {
return true; // All letters matched
}
if (row < 0 || row >= board.length || col < 0 || col >= board[0].length ||
visited[row][col] || board[row][col] != word.charAt(index)) {
return false; // Out of bounds or letter mismatch or already visited
}
visited[row][col] = true; // Mark current cell as visited
for (int[] dir : DIRECTIONS) {
int newRow = row + dir[0];
int newCol = col + dir[1];
if (backtrack(board, word, index + 1, newRow, newCol, visited)) {
return true; // Found valid path
}
}
visited[row][col] = false; // Backtrack: unmark cell
return false; // No path found from this cell
}
public static void main(String[] args) {
WordSearch ws = new WordSearch();
char[][] board = {
{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}
};
String word = "ABCCED";
System.out.println(ws.exist(board, word));
}
}if (board[r][c] == word.charAt(0)) {
Start search only from cells matching first letter
if (backtrack(board, word, 0, r, c, visited)) {
Try to find word starting from this cell
if (index == word.length()) { return true; }
All letters matched, word found
if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || visited[row][col] || board[row][col] != word.charAt(index)) { return false; }
Stop if out of bounds, visited, or letter mismatch
visited[row][col] = true;
Mark current cell as part of path
for (int[] dir : DIRECTIONS) { int newRow = row + dir[0]; int newCol = col + dir[1]; if (backtrack(board, word, index + 1, newRow, newCol, visited)) { return true; } }
Explore all four directions recursively
visited[row][col] = false;
Backtrack: unmark cell to allow other paths