From each pointer, spread to the board. One tricky is set the char that used to be 0. Set it back when finished searching.
1 class Solution { 2 private: 3 bool found; 4 int n, m; 5 public: 6 void findWord(vector<vector<char> > &board, int index, int row, int column, string word) { 7 if (word[index] != board[row][column] || found) { 8 return; 9 } 10 if (index == word.size()-1) { 11 found = true; 12 return; 13 } 14 char tmp = board[row][column]; 15 board[row][column] = 0; 16 if (row > 0) findWord(board, index+1, row-1, column, word); 17 if (row < n-1) findWord(board, index+1, row+1, column, word); 18 if (column > 0) findWord(board, index+1, row, column-1, word); 19 if (column < m-1) findWord(board, index+1, row, column+1, word); 20 board[row][column] = tmp; 21 } 22 bool exist(vector<vector<char> > &board, string word) { 23 if (board.size() == 0) return false; 24 n = board.size(), m = board[0].size(); 25 found = false; 26 for (int i = 0; i < n; i++) { 27 for (int j = 0; j < m; j++) { 28 findWord(board, 0, i, j, word); 29 if (found) return true; 30 } 31 } 32 return false; 33 } 34 };