# My accepted Java solution.12ms

• ``````public class Solution {
public boolean exist(char[][] board, String word) {
int row = board.length;
int col = board[0].length;
boolean[][] visited = new boolean[row][col];
char[] charOfWord = word.toCharArray();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (board[i][j] == charOfWord[0]) {
visited[i][j] = true;
boolean top = check(i-1, j, board, visited, charOfWord, 1);
boolean bottom = check(i+1, j, board, visited, charOfWord, 1);
boolean left = check(i, j-1, board, visited, charOfWord, 1);
boolean right = check(i, j+1, board, visited, charOfWord, 1);
if (top || bottom || left || right) {
return true;
}else {
visited[i][j] = false;
}
}
}
}
return false;
}
private boolean check(int r, int c, char[][] board, boolean[][] visited, char[] charOfWord, int index){
if (index >= charOfWord.length) {
return true;
}
int row = board.length;
int col = board[0].length;
if (r < 0 || r >= row || c < 0 || c >= col) {
return false;
}
if ((!visited[r][c]) && board[r][c] == charOfWord[index]) {
visited[r][c] = true;
boolean top = check(r-1, c, board, visited, charOfWord, index+1);
boolean bottom = check(r+1, c, board, visited, charOfWord, index+1);
boolean left = check(r, c-1, board, visited, charOfWord, index+1);
boolean right = check(r, c+1, board, visited, charOfWord, index+1);
if (top || bottom || left || right) {
return true;
}
else {
visited[r][c] = false;
return false;
}
}else {
return false;
}
}
``````

}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.