# 单词搜索 II

给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。

单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。

 

示例 1:

输入:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
输出:["eat","oath"]

示例 2:

输入:board = [["a","b"],["c","d"]], words = ["abcb"]
输出:[]

 

提示:

## template ```cpp #include using namespace std; class Solution { public: struct Node { bool isflag = false; Node *next[27] = {}; }; set res; vector ans; Node *root; vector dirx{0, 0, 1, -1}; vector diry{1, -1, 0, 0}; bool flag; void createtree(vector &words) { root = new Node(); for (auto w : words) { Node *p = root; for (int i = 0; i < w.length(); i++) { if (p->next[w[i] - 'a'] == NULL) { p->next[w[i] - 'a'] = new Node(); } p = p->next[w[i] - 'a']; } p->isflag = true; } } void backtrack(vector> &board, vector> visited, int row, int col, Node *roott, string cur) { cur += board[row][col]; roott = roott->next[board[row][col] - 'a']; if (!roott) return; if (roott->isflag == true) { res.insert(cur); flag = true; } visited[row][col] = true; for (int i = 0; i < 4; i++) { int nx = row + dirx[i]; int ny = col + diry[i]; if (nx < 0 || ny < 0 || nx >= board.size() || ny >= board[0].size()) continue; if (visited[nx][ny] == false) { backtrack(board, visited, nx, ny, roott, cur); } } } vector findWords(vector> &board, vector &words) { if (board.size() == 0 || words.size() == 0) return ans; createtree(words); for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[i].size(); j++) { Node *p = root; flag = false; if (p->next[board[i][j] - 'a']) { vector> visited{board.size(), vector(board[0].size(), false)}; backtrack(board, visited, i, j, p, ""); } } } set::iterator it; for (it = res.begin(); it != res.end(); it++) ans.push_back(*it); return ans; } }; ``` ## 答案 ```cpp ``` ## 选项 ### A ```cpp ``` ### B ```cpp ``` ### C ```cpp ```