LeetCode Word Search II

本文介绍了一种使用前缀树解决LeetCode上的单词搜索II问题的方法。通过构建前缀树来高效地在二维字符矩阵中查找给定单词列表中的所有单词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 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.

For example,
Given words = ["oath","pea","eat","rain"] and board =

[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
Return  ["eat","oath"] .

题目的意思是给定二维字符表和一些单词,然后返回能在字符表中找到的单词的集合。

解法:由于可能有很多的单词需要查找,单词一多,就有很多共有的前缀(如“abcd”和“abcf”的前缀是“abc”),这样一来就没有必要每个单词从头找起,于是想到了前缀树的解决方法:即把单词构建成前缀树,然后在字符表搜索,遇到满足题意的就加入结果集。

class Trie {
public:
	Trie* branch[26];
	bool isWord;//从根节点到当前节点组成的字符串是否是列表中的一个单词
	int index;//如果是列表中的一个单词,记录该单词在列表中的下标
public:
	Trie()
	{
		memset(branch, 0, sizeof(branch));
		isWord = false;
		index = 0;
	}
};

Trie* buildTrie(vector<string>& words)
{
	Trie* root = new Trie();
	for (int i = 0; i < words.size(); i++)
	{	
		Trie* p = root;
		for (int j = 0; j < words[i].size(); j++)
		{
			if (p->branch[words[i][j] - 'a'] == NULL)
			{
				p->branch[words[i][j] - 'a'] = new Trie();
			}
			p = p->branch[words[i][j] - 'a'];
		}

		p->isWord = true;
		p->index = i;//记录在words中的下标
	}

	return root;
}

void dfs(vector<vector<char> >& board, int i, int j, int row, int col, Trie* root, vector<string>& res, vector<string>& words)
{	
	if (board[i][j] == 'X')
		return;
	if (root->branch[board[i][j] - 'a'] == NULL)
		return;
	else
	{
		char t = board[i][j];
		if (root->branch[t - 'a']->isWord == true)
		{
			res.push_back(words[root->branch[t - 'a']->index]);//把words中位于index的单词加入结果集
			root->branch[t - 'a']->isWord = false;//标记次单词已访问过
		}

		board[i][j] = 'X';//标记已经搜索过
		//上下左右进行递归搜索
		if (i > 0)			dfs(board, i - 1, j, row, col, root->branch[t - 'a'], res, words);		
		if ((i + 1)<row)	dfs(board, i + 1, j, row, col, root->branch[t - 'a'], res, words);
		if (j > 0)			dfs(board, i, j - 1, row, col, root->branch[t - 'a'], res, words);
		if ((j + 1)<col)	dfs(board, i, j + 1, row, col, root->branch[t - 'a'], res, words);
		
		board[i][j] = t; //回溯
	}
}

vector<string> findWords(vector<vector<char> >& board, vector<string>& words) 
{
	vector<string> res;
	int row = board.size();
	if (row == 0)	return res;
	int col = board[0].size();
	if (col == 0)	return res;

	int wordLen = words.size(); 
	if (wordLen == 0)	return res;

	Trie *root = buildTrie(words);//把单词列表构建成前缀树

	for (int i = 0; i < row; i++)
	{
		for (int j = 0; j < col; j++)
		{
			//以每个字符作为起始点开始搜
			dfs(board, i, j, row, col, root, res, words);
		}
	}

	return res;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值