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.
Ideas:
The DFS approach is similar to solving the maze problem.
1) Find the beginning of the entrance, here is to find and value word[0] the same position
2) Start recursive lookup, Word[1],word[2]....word[word.size ()-1], and solve the maze problem, here is the requirement of adjacent lattice, so the upper and lower left and right four directions to find a suitable solution.
3) if Cur=word.size (), the representative has found all the characters of this word, returns success. The algorithm ends.
classSolution { Public:BOOLvisited[ -][ -];intstep[4][2];voidDfsintXintYintCurintLenstring&word, vector<vector<char> >&board,BOOL&flag) {if(flag)return;if(cur = = len) {flag =true;return; } for(intI=0;i<4; i++) {inttx = x + step[i][0];intty = y + step[i][1];if(TX >=0&& TX < Board.size () && ty >=0&& Ty < board[0].size () && (visited[tx][ty] = =false) && Board[tx][ty] = = Word[cur]) {Visited[tx][ty] =true; DFS (tx,ty,cur+1, Len,word,board,flag); Visited[tx][ty] =false; } } }voidInit () {memset(Visited,false,sizeof(visited)); step[0][0] =1; step[0][1] =0; step[1][0] = -1; step[1][1] =0; step[2][0] =0; step[2][1] =1; step[3][0] =0; step[3][1] = -1; }BOOLExist vector<vector<char> >&board,stringWord) {intI,j;if(word.size () = =0)return true; Init (); for(i=0; I<board.size (); i++) { for(j=0; j<board[0].size (); j + +) {if(board[i][j]==word[0]){BOOLFlag =false; VISITED[I][J] =true; DFS (I,J,1, Word.size (), Word,board,flag);if(flag)return true; VISITED[I][J] =false; } } }return false; }};
[Leetcode] Word Search