leetcode 79|212. Word Search 1|2

本文介绍了一种在二维网格中查找指定单词的算法,并通过两个具体问题实例展示了如何利用深度优先搜索(DFS)和字典树(Trie)来高效解决这类问题。第一个问题关注单一单词的查找,而第二个问题则涉及在网格中寻找多个单词。

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

79. Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can 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.

For example,
Given board = 

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

直接把每一位作为开头,然后递归找上下左右是不是,如果是,就移过去接着找。思路有点像DFS。



class Solution {
public:
	bool exist(vector<vector<char>>& board, string word)
	{
	    for(int i = 0; i < board.size(); i++)
	    {
	        for(int j = 0;j < board[0].size(); j++)
	        {
	            if (exist(board, i, j, word, 0))
	                return true;
	        }
	    }
	    return false;	
	}
	
	bool exist(vector<vector<char>>& board, int x, int y, string word, int index)
	{
	    if (index == word.size())
	        return true;
	    if (x < 0 || y < 0 || x >= board.size() || y >= board[0].size() || board[x][y] != word[index])
	        return false;
	    char cun = board[x][y];
	    board[x][y] = '0';
	    
	    if (exist(board,x-1,y,word,index+1) || exist(board,x+1,y,word,index+1) || exist(board,x,y-1,word,index+1) || exist(board,x,y+1,word,index+1))
	       return true;
            board[x][y] = cun;
	    return false;
	}
};



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

Note:
You may assume that all inputs are consist of lowercase letters a-z.

这个题如果按照第一题的做法肯定会超时,所以引入一个字典树(Trie Tree)的概念.

如果遇到矩阵类字符串一个一个字符深度遍历就使用 DFS + Trie


class TrieNode{
public:
    string words;
    TrieNode* child[26];
    
    TrieNode()
    {
        words = "";
        memset(child , 0, sizeof(TrieNode*) * 26);
    }
};

class Solution {
public:
    vector<string> findWords(vector<vector<char> > &board, vector<string> &words)
    {
        root = new TrieNode();
        for (int i = 0; i < words.size(); i++)
        {
            wordinsert(words[i]);
        }
        
        int row = board.size();
        int col = board[0].size();
        
        vector<vector<bool>> mask(row, vector<bool>(col, true));
        
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                if (root->child[board[i][j]-'a'] != 0)
                {
                    search(i, j, board, mask, root->child[board[i][j]-'a']);
                }
            }
        }
        
        return ret;
    }
    
    void search(int x,
                int y,
                vector<vector<char> > &board,
                vector<vector<bool> > &mask,
                TrieNode *p)
    {
        int a[4] = {0, 1, 0, -1};
        int b[4] = {1, 0, -1, 0};
        int row = board.size();
        int col = board[0].size();
         
        if (p->words != "")     //TrieNode->words存的是以这个为末尾的字符串,如果不为空,说明有一个这样的单词
        {
            ret.push_back(p->words);
            p->words = "";      //避免重复查找到
        }
        
        mask[x][y] = false;
        for (int i = 0; i < 4; i++)
        {
            int _x = x + a[i];
            int _y = y + b[i];
            
            if (!isvaild(_x, _y, row, col) ||
                !mask[_x][_y] ||
                p->child[board[_x][_y] - 'a'] == 0)
                continue;
            
            search(_x, _y, board, mask, p->child[board[_x][_y] - 'a']);
        }
        mask[x][y] = true;
    }
    
    bool isvaild(int x,int y,int row,int col)
    {
        return x >= 0 && x < row && y >= 0 && y < col;
    }
     
    void wordinsert(string s)  //创建字典树
    {
        TrieNode *p = root;
        for (int i = 0; i < s.size(); i++)
        {
            if (p->child[s[i] - 'a'] == 0)
            {
                p->child[s[i] - 'a'] = new TrieNode();
            }
            p = p->child[s[i] - 'a'];
        }
        p->words = s;
    }
    
    TrieNode *root;
    vector<string> ret;
};























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值