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

一刷
題解:
因為為了要快速判斷用dfs構(gòu)成的prefix是否存在鸟款,這里用trie來保存字典仰禽。

public class Solution {
    class TrieNode {
        TrieNode[] next = new TrieNode[26];
        String word;
    }
    
    public List<String> findWords(char[][] board, String[] words) {
        List<String> res = new ArrayList<>();
        TrieNode root = buildTrie(words);
        for(int i=0; i<board.length; i++){
            for(int j=0; j<board[0].length; j++){
                dfs(board, i, j, root, res);
            }
        }
        return res;
    }
    
    private void dfs(char[][] board, int i, int j, TrieNode node, List<String> res){
        if(i<0 || j<0 || i>=board.length || j>=board[0].length) return;
        char c = board[i][j];
        if(c == '#' || node.next[c - 'a'] == null) return;
        node = node.next[c-'a'];
        if(node.word!=null){//found
            res.add(node.word);
            node.word = null;
        }
        board[i][j] = '#';
        dfs(board, i-1, j, node, res);
        dfs(board, i+1, j, node, res);
        dfs(board, i, j-1, node, res);
        dfs(board, i, j+1, node, res);
        board[i][j] = c;
    }
    
    
    private TrieNode buildTrie(String[] words){
        TrieNode root = new TrieNode();
        for(String word : words){
            TrieNode node = root;
            for(char ch : word.toCharArray()){
                if(node.next[ch - 'a'] == null){
                    node.next[ch - 'a'] = new TrieNode();
                }
                node = node.next[ch - 'a'];
            }
            node.word = word;
        }
        return root;
    }
}

二刷
這里有兩個小細節(jié)值得注意瘦材,首先TrieNode出了有26個child, 還有一個String field, 可以遍于最后加入list中等限。
第二迟郎,如果遍歷到了這個單詞坎弯,將它置為null厦坛, 否則會重復(fù)露该,或者用set保存最終結(jié)果睬棚。

public class Solution {
    private class TrieNode{
        TrieNode[] child = new TrieNode[26];
        String word;
    }
    
    private TrieNode root = new TrieNode();
    
    public List<String> findWords(char[][] board, String[] words) {
        //buildTree
        List<String> res = new ArrayList<>();
        buildTree(words);
        for(int i=0; i<board.length; i++){
            for(int j=0; j<board[0].length; j++){
                dfs(board, i, j, root, res);
            }
        }
        return res;
    }
    
    
    private void dfs(char[][] board, int i, int j, TrieNode cur, List<String> res){
        if(i<0 || i>=board.length || j<0 || j>=board[0].length) return;
        char ch = board[i][j];
        if(ch == '#' || cur.child[board[i][j] - 'a'] == null) return;
        cur = cur.child[board[i][j] - 'a'];
        if(cur.word != null) {
            res.add(cur.word);
            cur.word = null;
        }
        board[i][j] = '#';
        dfs(board, i+1, j, cur, res);
        dfs(board, i-1, j, cur, res);
        dfs(board, i, j+1, cur, res);
        dfs(board, i, j-1, cur, res);
        board[i][j] = ch;
    }
    
    private void buildTree(String[] words){
        for(String word : words){
            TrieNode cur = root;
            for(int i=0; i<word.length(); i++){
                char ch = word.charAt(i);
                if(cur.child[ch - 'a'] == null){
                    cur.child[ch - 'a'] = new TrieNode();
                }
                cur = cur.child[ch - 'a'];
            }
            cur.word = word;
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市解幼,隨后出現(xiàn)的幾起案子抑党,更是在濱河造成了極大的恐慌,老刑警劉巖撵摆,帶你破解...
    沈念sama閱讀 217,084評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件底靠,死亡現(xiàn)場離奇詭異,居然都是意外死亡特铝,警方通過查閱死者的電腦和手機暑中,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評論 3 392
  • 文/潘曉璐 我一進店門壹瘟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人鳄逾,你說我怎么就攤上這事稻轨。” “怎么了雕凹?”我有些...
    開封第一講書人閱讀 163,450評論 0 353
  • 文/不壞的土叔 我叫張陵殴俱,是天一觀的道長。 經(jīng)常有香客問我枚抵,道長粱挡,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,322評論 1 293
  • 正文 為了忘掉前任俄精,我火速辦了婚禮询筏,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘竖慧。我一直安慰自己嫌套,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,370評論 6 390
  • 文/花漫 我一把揭開白布圾旨。 她就那樣靜靜地躺著踱讨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪砍的。 梳的紋絲不亂的頭發(fā)上痹筛,一...
    開封第一講書人閱讀 51,274評論 1 300
  • 那天,我揣著相機與錄音廓鞠,去河邊找鬼帚稠。 笑死,一個胖子當(dāng)著我的面吹牛床佳,可吹牛的內(nèi)容都是我干的滋早。 我是一名探鬼主播,決...
    沈念sama閱讀 40,126評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼砌们,長吁一口氣:“原來是場噩夢啊……” “哼杆麸!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起浪感,我...
    開封第一講書人閱讀 38,980評論 0 275
  • 序言:老撾萬榮一對情侶失蹤昔头,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后影兽,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體揭斧,經(jīng)...
    沈念sama閱讀 45,414評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,599評論 3 334
  • 正文 我和宋清朗相戀三年赢笨,在試婚紗的時候發(fā)現(xiàn)自己被綠了未蝌。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片驮吱。...
    茶點故事閱讀 39,773評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖萧吠,靈堂內(nèi)的尸體忽然破棺而出左冬,到底是詐尸還是另有隱情,我是刑警寧澤纸型,帶...
    沈念sama閱讀 35,470評論 5 344
  • 正文 年R本政府宣布拇砰,位于F島的核電站,受9級特大地震影響狰腌,放射性物質(zhì)發(fā)生泄漏除破。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,080評論 3 327
  • 文/蒙蒙 一琼腔、第九天 我趴在偏房一處隱蔽的房頂上張望瑰枫。 院中可真熱鬧,春花似錦丹莲、人聲如沸光坝。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽盯另。三九已至,卻和暖如春洲赵,著一層夾襖步出監(jiān)牢的瞬間鸳惯,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評論 1 269
  • 我被黑心中介騙來泰國打工叠萍, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留芝发,地道東北人。 一個月前我還...
    沈念sama閱讀 47,865評論 2 370
  • 正文 我出身青樓俭令,卻偏偏與公主長得像后德,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子抄腔,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,689評論 2 354

推薦閱讀更多精彩內(nèi)容