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
.
Basic ideas:
1. Perform an in-depth search of each point on the board.
2. Traditional ASCII code, only use 7bit, the highest bit is 0. Therefore, this bit can be used as the access flag bit.
Class Solution {Public:bool exist (vector<vector<char> > &board, String Word) {if (Board.empty ( ) || Board[0].empty ()) return false; for (int i=0; I<board.size (), i++) {for (int j=0; j<board[0].size (); j + +) {if (exist (boa Rd, Word, 0, I, j)) return true; }} return false; } bool Exist (vector<vector<char> >&board, const string &word, int index, int x, int y) { if (index = = word.size ()) return true; if (x<0 | | y<0 | | x==board.size () | | y==board[0].size ()) return false; if (board[x][y]! = Word[index]) return false; Board[x][y] ^= 128; const BOOL existed = exist (board, Word, index+1, X, y+1) | | exist (board, Word, index+1, X, y-1) | | exist (board, Word, index+1, x+1, y) | | exist (board, Word, index+1, x-1, y); Board[x][y] ^= 128; return existed; }};
Word Search--Leetcode