Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.

class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || word == null || board.length == 0 || board[0].length == 0) {
return false;
}

int rows = board.length;
int cols = board[0].length;

boolean[][] visit = new boolean[rows][cols];

// i means the index.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// dfs all the characters in the matrix
if (dfs(board, i, j, word, 0, visit)) {
return true;
}
}
}

return false;
}

public boolean dfs(char[][] board, int i, int j, String word, int wordIndex, boolean[][] visit) {
int rows = board.length;
int cols = board[0].length;

int len = word.length();
if (wordIndex >= len) {
return true;
}

// the index is out of bound.
if (i < 0 || i >= rows || j < 0 || j >= cols) {
return false;
}

// the character is wrong.
if (word.charAt(wordIndex) != board[i][j]) {
return false;
}

// 不要访问访问过的节点
if (visit[i][j] == true) {
return false;
}

visit[i][j] = true;

// 递归
// move down
if (dfs(board, i + 1, j, word, wordIndex + 1, visit)) {
return true;
}

// move up
if (dfs(board, i - 1, j, word, wordIndex + 1, visit)) {
return true;
}

// move right
if (dfs(board, i, j + 1, word, wordIndex + 1, visit)) {
return true;
}

// move left
if (dfs(board, i, j - 1, word, wordIndex + 1, visit)) {
return true;
}

// 回溯
visit[i][j] = false;
return false;
}
}
class Solution {
public boolean exist(char[][] board, String word) {
if(board == null || board.length == 0 || board[0] == null || board[0].length == 0 || word == null || word.length() == 0)
return false;

boolean[][] isVisited = new boolean[board.length][board[0].length];
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(dfs(board, word, i, j, 0, isVisited))
return true;
}
}
return false;
}
private boolean dfs(char[][] board, String word, int i, int j, int index, boolean[][] isVisited){
int row = board.length;
int col = board[0].length;

// return case
if(word.length() == index) return true;
// fail case
if(i < 0 || i >= row || j < 0 || j >= col || board[i][j] != word.charAt(index) || isVisited[i][j])
return false;
// do dfs
isVisited[i][j] = true;
boolean res = dfs(board, word, i+1, j, index+1, isVisited) || dfs(board, word, i-1, j, index+1, isVisited) || dfs(board, word, i, j+1, index+1, isVisited) || dfs(board, word, i, j-1, index+1, isVisited);
isVisited[i][j] = false;

return res;
}
}