[leetcode]Word Search II

来源:互联网 发布:破解版软件下载 编辑:程序博客网 时间:2024/04/28 05:51

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;    };


0 0
原创粉丝点击