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']);
			}
		}
	}
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值