Use DFS to find the possible path that match the string;
Code:
public class Solution { public boolean exist(char[][] board, String word) { if(word == null) return false; int row = board.length; int col = board[0].length; int count = word.length(); boolean flag = false; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ if(board[i][j] == word.charAt(0)){ boolean[][] mark = new boolean[row][col]; if(checkLetter(count-1, word, 0, board, i, j, row, col, mark)) return true; } } } return false; } public boolean checkLetter(int n, String s, int i, char[][] board, int x, int y, int row, int col, boolean[][] isMarked){ char letter = s.charAt(i); char c = board[x][y]; boolean flag = false; if(letter != c) return false; else{ isMarked[x][y] = true; if(i == n) return true; if((x+1) < row && !isMarked[x+1][y]) { if(checkLetter(n, s, i+1, board, x+1, y, row, col, isMarked)) return true; } if((x-1) >= 0 && !isMarked[x-1][y]) { if(checkLetter(n, s, i+1, board, x-1, y, row, col, isMarked)) return true; } if((y+1) < col && !isMarked[x][y+1]) { if(checkLetter(n, s, i+1, board, x, y+1, row, col, isMarked)) return true; } if((y-1) >= 0 && !isMarked[x][y-1]) { if(checkLetter(n, s, i+1, board, x, y-1, row, col, isMarked)) return true; } isMarked[x][y] = false; return false; } } }