LeetCode212 Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must 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 in a word.

Example:

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

Output: ["eat","oath"]

Note:

  1. All inputs are consist of lowercase letters a-z.
  2. The values of words are distinct.

思路:

如果我们直接暴力求解的话会导致时间过长,所以我们这里需要借助字典树这个数据结构:我们使用字典树保存所有的word,然后在依次dfs输入board中的每一个entry。代码如下:

class Solution {
public:
	vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
		genTree(words);
		for (int i = 0; i < board.size(); i++) {
			for (int j = 0; j < board[0].size(); j++) {
				DFS(board, { i, j }, root);
			}
		}
		vector<string> resVec(res.begin(), res.end());
		return resVec;
	}
private:
	struct Node {
		string word;
		Node *childs[26];
		Node() : word("") { memset(childs, 0, sizeof(childs)); }
	};

	Node *root;
	set<string> res;
	void genTree(const vector<string> &words) {
		root = new Node();
		for (string word : words) {
			Node *curr = root;
			for (char letter : word) {
				curr =
					curr->childs[letter - 'a'] == 0 ?
					curr->childs[letter - 'a'] = new Node() :
					curr->childs[letter - 'a'];
			}
			curr->word = word;
		}
	}

	void DFS(vector<vector<char>> board, pair<int, int> coor, Node *curr) {		
		char letter = board[coor.first][coor.second];
		if (letter == '.') return;
		board[coor.first][coor.second] = '.';

		vector<pair<int, int>> neighbors;
		if (coor.first > 0) neighbors.push_back({ coor.first - 1, coor.second });
		if (coor.first < board.size() - 1) neighbors.push_back({ coor.first + 1, coor.second });
		if (coor.second > 0) neighbors.push_back({ coor.first, coor.second - 1 });
		if (coor.second < board[0].size() - 1) neighbors.push_back({ coor.first, coor.second + 1 });

		if (curr->childs[letter - 'a'] != 0) {
            if (curr->childs[letter - 'a']->word != "") res.insert(curr->childs[letter - 'a']->word);
			for (pair<int, int> neighbor : neighbors) {
				DFS(board, neighbor, curr->childs[letter - 'a']);
			}
		}
	}
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/89313568