Word Search
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 is those horizontally or V Ertically neighboring. The same letter cell is used more than once.
For example,
Given Board =
[ ["ABCE"], ["SFCs"], ["Adee"]]
Word=
"ABCCED"
, returns
true
,
Word=
"SEE"
, returns
true
,
Word=
"ABCB"
, returns
false
. Idea: DFS algorithm. Note: Because each character can only match once, the match succeeds in placing the character as a useless character, such as ' # ', and then continues to match the next character.
classsolution{ Public: Solution (): IsTrue (false) {}Private: voidDFS (vector<vector<Char> > &board,stringWordintXintYintindex) { if(Index = =word.size ()) {IsTrue=true; return; } if(isTrue)return; if(X <0|| x >= board.size ())return; if(Y <0|| Y >= board[0].size ())return; if(Board[x][y]! = Word[index])return; Board[x][y]='#'; DFS (board, Word, x-1, Y, index+1); DFS (board, Word, x+1, Y, index+1); DFS (board, Word, x, y-1, index+1); DFS (board, Word, x, y+1, index+1); Board[x][y]=Word[index]; } Public: BOOLexist (vector<vector<Char> > &board,stringword) { if(Board.empty () | | board[0].empty ())return false; IsTrue=false; intindex =0; for(intI=0; I<board.size (); i++) { for(intj=0; j<board[0].size (); J + +) { if(!isTrue) DFS (board, Word, I, J, index); } } returnisTrue; }Private: BOOLisTrue;};
[Leetcode] Word Search