1. 程式人生 > >Word Search 和 Word Search Ⅱ

Word Search 和 Word Search Ⅱ

總程式碼如下:

class Solution {
public:

    struct TrieNode
    {
        TrieNode *child[26];
        string node;
        TrieNode():node("")
        {
            for(auto &a:child)
                a=NULL;
        }
    };
    struct Trie
    {
        TrieNode *root;
        Trie():root(new TrieNode()){}
        void
insert(string s) { TrieNode *p=root; for(auto &str:s) { int i=str-'a'; if(!p->child[i]) { p->child[i]=new TrieNode(); } p=p->child[i]; } p->node =s; } }; vector<string> findWords(vector<vector<char
>>& board, vector<string>& words) { vector<string> result; if(board.empty()||board[0].empty()||words.empty()) return result; vector<vector<bool>> dp(board.size(),vector<bool>(board[0].size(),false)); Trie T; for
(auto &s:words) T.insert(s); for(int i=0;i<board.size();i++) { for(int j=0;j<board[0].size();j++) { if(T.root->child[board[i][j]-'a']) { dp[i][j]=true;//表示當前 節點 已經走過 WordSearch(board,T.root->child[board[i][j]-'a'],i,j,dp,result); dp[i][j]=false;//去掉走過的痕跡 } } } return result; } void WordSearch(vector<vector<char>>& board,TrieNode *p,int i,int j,vector<vector<bool>> &dp,vector<string> &result) { if(!p->node.empty())//如果當前字典樹位於Node處,表示有單詞,找到一次,將該單詞處的標記清除,繼續往下找 { result.push_back(p->node); p->node.clear(); } int direction[4][2]={-1,0,0,1,1,0,0,-1};//定義四個方向 for(int k=0;k<4;k++) { int new_i=i+direction[k][0]; //新的i int new_j=j+direction[k][1]; //新的j //跟上面同樣的思想,把新的節點看成當前節點繼續往前查詢 if(new_i>=0&&new_i<board.size()&&new_j>=0&&new_j<board[0].size()&&dp[new_i][new_j]==false&&p->child[board[new_i][new_j]-'a']) { dp[new_i][new_j]=true; WordSearch(board,p->child[board[new_i][new_j]-'a'],new_i,new_j,dp,result); dp[new_i][new_j]=false; } } } };