(Daily algorithm) LeetCode --- Word Search (Search words in the matrix)
Search for the occurrence of a given word in the Matrix. You can search up, down, left, or right. You cannot repeat 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 are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"]]
Word =
"ABCCED"
,-> Returns
true
,
Word =
"SEE"
,-> Returns
true
,
Word =
"ABCB"
,-> Returns
false
.
// How to construct parameters of helper functions? // How do I transmit the next letter to be matched when matching letters one by one? --- Through the form of index parameters // The path to be marked, whether feasible or not, must be re-marked? // What are the boundary conditions? Class Solution {public: bool exist (vector
> & Board, string word) {const int m = board. size (); const int n = board [0]. size (); vector
> Visited (m, vector
(N, false); // leave the access tag array empty for (int I = 0; I <m; I ++) for (int j = 0; j <n; j ++) if (dfs (board, word, 0, I, j, visited) // return true can be matched at any position; // if there is a exact match, return false is matched;} static bool dfs (vector
> & Board, string word, int index, int x, int y, vector
> & Visited) // auxiliary function, custom parameter {if (index = word. size () // The word size is equal to the index, that is, match. // when the word is empty, it is satisfied. // The next index to be searched and the word size are equal, // The 0-index letter of the word matches return true; if (x <0 | y <0 | x> = board. size () | y> = board [0]. size () // return false; if (visited [x] [y]) // if you have accessed the API before, return false; if (board [x] [y]! = Word [index]) // if the path is not the same, return false for pruning; visited [x] [y] = true; // mark it as walking first, because the next time bool ret = dfs (board, word, index + 1, x, y + 1, visited) is going in four directions | 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 through, but it does not match. It must be restored to return ret ;}};