shriyanshi24jindal

Word Search

Mar 30th, 2026
130
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 9.11 KB | None | 0 0
  1. class Solution {
  2. /**
  3.   We try to match the word character by character by exploring neighbors.
  4.   At any cell (i, j):
  5.   - If it matches word[index], we try all 4 directions
  6.   - Move to next index (index + 1)
  7.   - If path fails → backtrack
  8.   */
  9. public boolean exist(char[][] board, String word) {
  10. int n = board.length;
  11. int m = board[0].length;
  12.  
  13. for(int i=0; i<n; i++)
  14. {
  15. for(int j=0; j<m; j++)
  16. {
  17. if(dfs(board, word, i, j, 0))
  18. return true;
  19. }
  20. }
  21. return false;
  22. }
  23.  
  24.  
  25. public boolean dfs(char[][] board, String word, int row, int col, int index)
  26. {
  27. int n = board.length;
  28. int m = board[0].length;
  29.  
  30. // base case
  31. if(index == word.length())
  32. return true;
  33.  
  34. // invalid case
  35. if(row < 0 || col < 0 || row >= n || col >= m || board[row][col] != word.charAt(index))
  36. {
  37. return false;
  38. }
  39.  
  40. // mark visited
  41. char temp = board[row][col];
  42. board[row][col] = '#';
  43.  
  44. // explore all 4-directions
  45. boolean result = dfs(board, word, row+1, col, index+1) ||
  46. dfs(board, word, row, col+1, index+1) ||
  47. dfs(board, word, row-1, col, index+1) ||
  48. dfs(board, word, row, col-1, index+1);
  49.  
  50. // backtrack
  51. board[row][col] = temp;
  52. return result;
  53. }
  54. }
RAW Paste Data Copied