Describe
Give a two-dimensional letter board and a word to find out if the word is present in the letter Board grid.
Words can consist of the letters of adjacent cells in order, in which adjacent cells refer to the horizontal or vertical direction adjacent. The letters in each cell can be used at most once.
Sample Example
Give the
board =
[
"ABCe",
"SFCs",
"Adee"]
Word = "abcced", and returns True,
Word = "See",-> returns True,
Word = "ABCB", and returns false.
Class Solution {public:/** * @param board:a List of lists of character * @param word:a String * @return: A Boolean */bool exist (vector<vector<char>> &board, string &word) {//write your code Here/write your code here vector< vector<bool> > Mask (board.size (), VECTOR<BOOL&G t; (Board[0].size (), false)); for (int i=0; I<board.size (), ++i) {for (int j=0; j<board[0].size (); ++j) {if (Search (bo ARD, Word, mask, I, J, 0)) {return true; }}} return false; } bool Search (vector< vector<char> >& Board, String Word, vector< vector<bool> >& m Ask, int i, int j, int idx) {if (Word[idx]==board[i][j]) {mask[i][j] = true; ++idx; if (idx = = Word.size ()) return true; else if (i-1>=0 &&!mask[i-1][j] &&Search (board, Word, Mask, i-1, J, IDX)) return true; else if (i+1< board.size () &&!mask[i+1][j] && Search (board, Word, Mask, i+1, J, IDX)) return true; else if (j-1>=0 &&!mask[i][j-1]&& Search (board, Word, mask, I, j-1, idx)) return true; else if (j+1< board[0].size () &&!mask[i][j+1] && Search (board, Word, mask, I, j+1, idx)) return True else {Mask[i][j] = false; return false; } } }};
123. Word Search (DFS)