[leetcode]Word Search II

LeetCode单词搜索II题解
本文介绍了一种使用字典树(Trie)结构解决LeetCode上的单词搜索II问题的方法。通过构建字典树来高效查找给定二维字母板上出现的所有字典中的单词。该算法采用深度优先搜索策略,结合回溯思想,确保每个字母只被使用一次构建单词。

from : https://leetcode.com/problems/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"].

class Solution {
public:
    struct TrieNode {
        bool isWord;
        TrieNode *nextNodes[26];

		TrieNode(): isWord(false){
			for(TrieNode*& c : nextNodes) {
				c = NULL;
			}
		}
		
		void becomeWord() {
			isWord = true;
		}

		void setNext(char next) {
			nextNodes[next-'a'] = new TrieNode();
		}

		TrieNode* next(char next) {
			return nextNodes[next-'a'];
		}

    };

	struct Trie {
		Trie() {
			root = new TrieNode();
		}

		void insert(string& word) {
			TrieNode *p = root;
			for(char c : word) {
				if(NULL == p->next(c)) {
					p->setNext(c);
				}
				p = p->next(c);
			}
			p->becomeWord();
		}

		bool containWordStartWith(char character) {
			return NULL != root->nextNodes[character-'a'];
		}

		TrieNode* begin() {
			return root;
		}

	private :
		TrieNode *root;
	};

	bool isWithinBoundry(int i, int j) {
		if(i<0 || i>=m || j<0 || j>=n) {
			return false;
		}
		return true;
	}

	void find(vector<vector<char>>& board, int i, int j, set<string>& st, vector<vector<bool>>& visit, string& str, TrieNode* trienode) {
		trienode = trienode->next(board[i][j]);	
		if(!trienode) return;

		visit[i][j] = true;
		str.push_back(board[i][j]);
		if(trienode->isWord) {
			st.insert(str);
		}

		int dx[] = {1,0,-1,0};
		int dy[] = {0,1,0,-1};
		int x, y;
		for(int k=0; k<4; ++k) {
			x = i + dx[k];
			y = j + dy[k];
			if(isWithinBoundry(x, y) && !visit[x][y]) {
				if(trienode->next(board[x][y])) {
					find(board, x, y, st, visit, str, trienode);
				}
			}
		}
		
		str.pop_back();
		visit[i][j] = false;
	}


    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> res;
		if(words.empty() || board.empty() || board[0].empty()) {
			return res;
		}
		Trie trie;
		for(string& s : words) {
			trie.insert(s);
		}
		m = board.size(), n = board[0].size();
		vector<vector<bool>> visit(m, vector<bool>(n, false));
		set<string> st;
		string str;

		for(int i=0; i<m; ++i) {
			for(int j=0; j<n; ++j) {
				if(trie.containWordStartWith(board[i][j])) {
					find(board, i, j, st, visit, str, trie.begin());
				}
				
			}
		}
		for(string s : st) {
			res.push_back(s);
		}
		return res;
    }
private:
	int m;
	int n;    
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值