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
.
This problem is a typical depth-first traversal of DFS application, the original two-dimensional array is like a maze, can walk up and down in four directions, we take a two-dimensional array of each number as a starting point and a given string to match, we also need a and the original array size visited array, is bool type, Used to record whether the current location has been accessed, because the topic requires that a cell be accessed only once. If the current character of the two-dimensional array board is equal to the character of the target string word, then the recursive function of Dfs is called by the four adjacent characters up and down, so long as one returns true, it means that the corresponding string can be found, otherwise, the code implementation is as follows:
classSolution { Public: BOOLexist (vector<vector<Char> > &board,stringword) { if(Word.empty ())return true; if(Board.empty () | | board[0].empty ())return false; Vector<vector<BOOL> > Visited (board.size (), vector<BOOL> (board[0].size (),false)); for(inti =0; I < board.size (); ++i) { for(intj =0; J < Board[i].size (); ++j) {if(Search (board, Word,0, I, J, visited))return true; } } return false; } BOOLSearch (vector<vector<Char> > &board,stringWordintIdxintIintJ, vector<vector<BOOL> > &visited) { if(idx = = Word.size ())return true; if(I <0|| J <0|| I >= board.size () | | J >= board[0].size () | | VISITED[I][J] | | BOARD[I][J]! = Word[idx])return false; VISITED[I][J]=true; BOOLres = search (board, Word, IDX +1I1, J, visited)|| Search (board, Word, IDX +1, i +1, J, visited)|| Search (board, Word, IDX +1, I, J-1, visited)|| Search (board, Word, IDX +1, I, J +1, visited); VISITED[I][J]=false; returnRes; }};
[Leetcode] Word Search words