Leetcode 212. Word Search II (tries树 + DFS)

2023-05-16

题目:

 

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"]

 

一开始尝试了简单的DFS搜索,算法复杂度很高。

单独DFS版本代码:

class Solution {
public:
	vector<vector<char>> b;
	vector<string> ans;
	string s;
	int m;
	int n;
	void helper(string ss){
		s=ss;
		for(int i=0;i<m;i++){
			for(int j=0;j<n;j++){
				if(b[i][j]!=s[0]) continue;
				if(dfs(i,j,0)){
					ans.push_back(s);
					return;
				}
			}
		}
	}
	bool dfs(int x, int y,int d){    
		if(x<0 || x>=m ||y<0 || y>=n || s[d]!=b[x][y]) return false;
		if(d==s.size()-1) return true;
		char cur=b[x][y];
		b[x][y]='#';
		bool found=dfs(x+1,y,d+1) ||
				   dfs(x-1,y,d+1) ||
				   dfs(x,y+1,d+1) ||
				   dfs(x,y-1,d+1);
		b[x][y]=cur;
		return found;  
	}
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        b=board;
		m=board.size();
		n=board[0].size();
		for(int i=0;i<words.size();i++){
			helper(words[i]);
		}   
		return ans;  
    }
};

尝试加入 tries树,算法复杂度降低很多

tries树 + DFS:

class Solution {
public:
    struct TrieNode {
        TrieNode *child[26];
        string str;
        TrieNode() : str("") {
            for (auto &a : child) a = NULL;
        }
    };
    struct Trie {
        TrieNode *root;
        Trie() : root(new TrieNode()) {}
        void insert(string s) {
            TrieNode *p = root;
            for (auto &a : s) {
                int i = a - 'a';
                if (!p->child[i]) p->child[i] = new TrieNode();
                p = p->child[i];
            }
            p->str = s;
        }
    };
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> res;
        if (words.empty() || board.empty() || board[0].empty()) return res;
        vector<vector<bool>> visit(board.size(), vector<bool>(board[0].size(), false));
        Trie T;
        for (auto &a : words) T.insert(a);
        for (int i = 0; i < board.size(); ++i) {
            for (int j = 0; j < board[i].size(); ++j) {
                if (T.root->child[board[i][j] - 'a']) {
                    search(board, T.root->child[board[i][j] - 'a'], i, j, visit, res);
                }
            }
        }
        return res;  
    }
    void search(vector<vector<char>>& board, TrieNode* p, int i, int j, vector<vector<bool>>& visit, vector<string>& res) { 
        if (!p->str.empty()) {
            res.push_back(p->str);
            p->str.clear();
        }
        int d[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        visit[i][j] = true;
        for (auto &a : d) {
            int nx = a[0] + i, ny = a[1] + j;
            if (nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].size() && !visit[nx][ny] && p->child[board[nx][ny] - 'a']) {
                search(board, p->child[board[nx][ny] - 'a'], nx, ny, visit, res);
            }
        }
        visit[i][j] = false;
    }
};

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Leetcode 212. Word Search II (tries树 + DFS) 的相关文章

  • 使用批量/更新方法将“标签”应用于数百万个文档

    我们的 ElasticSearch 实例中有大约 55 000 000 个文档 我们有一个带有 user ids 的 CSV 文件 最大的 CSV 有 9M 个条目 我们的文档以 user id 作为键 所以这很方便 我发布这个问题是因为我
  • IP 地址的索引范围搜索算法

    给定一个包含 100 亿个以 CIDR 表示法表示的 IPv4 范围或两个 IP 之间的 ACL 列表 x x x x y x x x x y y y y 用于测试给定 IP 地址是否满足一个或多个 ACL 范围条件的有效搜索 索引算法是什
  • 列表视图过滤器 Android

    我在android中创建了一个列表视图 我想在列表上方添加编辑文本 当用户输入文本时 列表将根据用户输入进行过滤 谁能告诉我是否有办法在android中过滤列表适配器 在列表视图的 xml 布局文件中添加一个 EditText 在你的活动
  • iOS 使用查询打开 YouTube 应用程序(url 方案)

    是否有 URL 方案可以使用指定的搜索查询打开 YouTube iOS 应用程序 I tried NSString stringURL http www youtube com results search query foo NSURL
  • 如何在linux中查找包含字符串的行[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我在 Linux 中有一个文件 我想显示该文件中包含特定字符串的行 该怎么做 通常的方法是使用grep https linux die n
  • 仅根据lucene中term出现次数较多的文档来计算分数

    我开始研究基于 lucene net 引擎的简历检索 文档 组件 它工作得很好 它会获取文档并根据 VSM 背后的理念是 查询词出现在 a 中的次数 文档相对于数量 该术语出现在所有 集合中的文档越多 该文件的相关内容是 询问 Lucene
  • Solr 高亮显示

    我看到了这个帖子here https stackoverflow com questions 4058913 how to highlighting search results using apache solr with php cod
  • 如何使用 Delphi XE2 IDE 搜索来搜索

    我一直使用搜索来在 庞大的 应用程序源中查找内容 因此搜索有效性对我来说非常重要 目前在 Delphi XE2 IDE 中我喜欢使用 在文件中查找 包括子目录 没有其他花哨的东西 只是一个文本关键字 这工作正常 但我真正想做的是扩展我现在正
  • 从 Visual Studio 搜索中排除特定文件

    是否可以从 Visual Studio 中的搜索中排除某些文件 例如 jquery js 几乎总是污染我的搜索结果 一半结果来自该文件 我知道您可以将特定类型列入白名单 但是当我想在 js 扩展名中搜索时 有解决方案吗 在这里投票功能 ht
  • 在 mysql 中搜索带变音符号的阿拉伯语

    所以我有一个巨大的带有变音符号的阿拉伯语书面文本数据库 变音符号是阿拉伯语中附加到其他字符的小字符 例如 带变音符号 不带变音符号 我正在使用 mysql 和 laravel 在文本中搜索没有变音符号的特定单词 如何忽略搜索中的变音符号 看
  • 为什么使用 Dijkstra 算法而不是最佳(最便宜)优先搜索?

    从我到目前为止所读到的来看 这最佳优先搜索 https en wikipedia org wiki Best first search在找到到达目标的最短路径方面似乎更快 因为 Dijkstra 算法在遍历图时必须放松所有节点 是什么让 D
  • 如何实现 IFilter 来索引重量级格式?

    我需要为 Microsoft Search Server 2008 开发一个 IFilter 它执行长时间的计算来提取文本 从一个文件中提取文本可能需要 5 秒到 12 小时 我如何设计这样的 IFilter 以便守护进程不会在超时时重置它
  • 在java中使用自定义比较器在数组中搜索

    为什么总是返回49999无论strToSearch变量保持 即使使用 clank 搜索变量 它也会返回相同的结果 我是不是错过了什么 String arr new String 100000 String strToSearch 12 fo
  • 如何搜索 Google 电子表格?

    我正在进行一些详尽的搜索 需要确定电子表格中是否已存在新域 URL 然而 所有 Spreadsheet 对象都没有搜索功能 即大多数 Document 对象中的 findText 功能 我觉得我错过了一些重要的事情 我缺少什么 查找文本函数
  • 自定义 Tridion 搜索索引处理程序:页面 url 的自定义字段与标准字段?

    我正在研究 SDL Tridion 2011 GA 的自定义搜索索引处理程序 我得到了一些工作 使用Arjen 提供的非常有用的信息 http 80000ft blogspot nl 2012 08 search indexing hand
  • 在数据框中搜索唯一值并用它们创建表

    自从我不久前开始使用 R URL 将类似于此示例格式 可在 源 列中找到 URL 中对我来说很重要的部分是 utm source ADX 位 我的数据如下所示 用户 来源 1 2 3 我需要做的是从 URL 中捕获 utm source 并
  • Android 搜索界面未提交查询

    我按照官方教程实现了一个搜索界面 搜索小部件 搜索界面 http developer android com training search setup html密切 一切看起来都不错 但我无法提交搜索查询 当我单击键盘上的 发送 按钮时
  • 自定义“可搜索”搜索字段 SwiftUI iOS 15

    When using the new searchable modifier in SwiftUI on iOS 15 I have no way to customize the Search Bar appearance Specifi
  • 在 O(n) 时间内找到 n x n 矩阵中的局部最小值

    所以 这不是我的家庭作业问题 而是取自 coursera 算法和数据结构课程的未评分作业 现已完成 You are given an n by n grid of distinct numbers A number is a local m
  • Elasticsearch 关于“空索引”的查询

    在我的应用程序中 我使用了几个elasticsearch索引 它们在初始状态下不包含索引文档 我认为这可以称为 空 该文档的映射是正确且有效的 该应用程序还有一个包含实体的关系数据库 这些实体可能具有在 elasticsearch 中关联的

随机推荐