Skip to content

Instantly share code, notes, and snippets.

@anil477
Created January 30, 2022 09:17
Show Gist options
  • Save anil477/3bf185fa5503c65fc7781fc1396b013d to your computer and use it in GitHub Desktop.
Save anil477/3bf185fa5503c65fc7781fc1396b013d to your computer and use it in GitHub Desktop.
79. Word Search
public class Solution {
// 79. Word Search
// https://leetcode.com/problems/word-search/
public boolean exist(char[][] board, String word) {
for(int i = 0; i < board.length; i++)
for(int j = 0; j < board[0].length; j++){
if (board[i][j] == word.charAt(0)) {
if(exist(board, i, j, word, 0))
return true;
}
}
return false;
}
private boolean exist(char[][] board, int i, int j, String word, int ind){
if(ind == word.length()) return true;
if(i > board.length-1 || i <0 || j<0 || j >board[0].length-1 || board[i][j]!=word.charAt(ind))
return false;
board[i][j]='*';
boolean result = exist(board, i-1, j, word, ind+1) ||
exist(board, i, j-1, word, ind+1) ||
exist(board, i, j+1, word, ind+1) ||
exist(board, i+1, j, word, ind+1);
board[i][j] = word.charAt(ind);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment