LeetCode Problem description here.
Given an m x n
grid of characters board and a string word, return true if 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.
Input:
[["a","a","b","a","a","b"],
["a","a","b","b","b","a"],
["a","a","a","a","b","a"],
["b","a","b","b","a","b"],
["a","b","b","a","b","a"],
["b","a","a","a","a","b"]]
word to find :"bbbaabbbbbab"
Output: true
Expected: false
class Solution {
public boolean exist(char[][] board, String word) {
if (word.equals(null)) {
return false;
}
Stack<String> path = new Stack<String>();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
boolean foundWord = dfs(board,i, j, 0, word,path);
if (foundWord == true) {
return true;
}
}
}
return false;
}
private boolean dfs(char [][] board,int i, int j, int wordIndex, String word, Stack<String> path) {
if (!path.contains("(" + String.valueOf(i) + "," + String.valueOf(j) + ")"))
{
path.push("(" + String.valueOf(i) + "," + String.valueOf(j) + ")");
}
if (wordIndex == word.length()) {
return true;
}
if (i < 0 || j < 0 || i >= board.length || j >= board[i].length){
path.pop();
return false;
}
else if (board[i][j] != word.charAt(wordIndex)) {
path.pop();
return false;
}
char oldLetter = board[i][j];
board[i][j]='*';
boolean foundWord = dfs(board,i, j - 1, wordIndex + 1, word,path) || dfs(board,i, j + 1, wordIndex + 1, word,path)
|| dfs(board,i - 1, j, wordIndex + 1, word,path) || dfs(board,i + 1, j, wordIndex + 1, word,path)
|| dfs(board,i + 1, j + 1, wordIndex + 1, word,path);
board[i][j]=oldLetter;
return foundWord;
}
}