Finds whether a given word appears in the matrix and can be looked up, down, left, and right. You cannot repeat a search on a letter.
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
.
How do I construct parameters for auxiliary functions? How do you pass the next letter that you want to match, one letter at a time? ---to mark by the form of an index parameter//pass through the road, whether it is feasible or not, to be marked again? Consideration of boundary conditions? Class Solution {Public:bool exist (vector<vector<char>> &board, string word) {const int m = Boa Rd.size (); const int n = board[0].size (); Vector<vector<bool>> visited (m, vector<bool> (n, false));//The access token array is empty for (int i = 0; i < m; i++) for (int j = 0; J < N; j + +) if (DFS (board, Word, 0, I, J, visited))//words can start matching at any location return true; As long as there is a position exactly match that matches return false; } static bool Dfs (vector<vector<char>> &board, string word, int index, int x, int y, vector<vector<bool>>& visited)//auxiliary function, custom parameter {if (index = = word.size ())//Word size and index equal match When the word is empty is satisfied//next to find the index and Word size equal description, The letter of the location of Word's 0-index has been matched return true; if (x < 0 | | Y < 0 | | x >= board.size () | | y >= board[0].size ())//non-crossed return false; if (Visited[x][y])//If previously accessed, then direct return false to false; if (board[x][y]! = Word[index])//Unequal, this road does not go through, pruning return false; Visited[x][y] = true; Mark first as traversed, because next time will go four directions bool ret = DFS (board, Word, index + 1, x, y + 1, visited) | | DFS (board, Word, index + 1, x, y-1, visited) | | DFS (board, Word, index + 1, x-1, y, visited) | | DFS (board, Word, index + 1, x + 1, y, visited); Visited[x][y] = false; After passing, but does not match, to revert to not traversed return ret; }};
(Daily algorithm) Leetcode---Word search (find words in a matrix)