212. Word Search II

Question

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

Code

class TrieNode {
    boolean end;
    Map<Character, TrieNode> sons;
    String s;
    
    public TrieNode() {
        sons = new HashMap<>();
    }
}

class Trie {
    public TrieNode root;
    
    public Trie() {
        root = new TrieNode();
    }
    
    public void insert (String s) {
        if (s == null || s.length() == 0) return;
        TrieNode node = root;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!node.sons.containsKey(c)) {
                TrieNode newNode = new TrieNode();
                node.sons.put(c, newNode);
            }
            node = node.sons.get(c);
        }
        node.end = true;
        node.s = s;
    }
    
    public boolean search(String s) {
        if (s == null || s.length() == 0) return true;
        
        TrieNode node = root;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (node.sons.containsKey(c)) {
                node = node.sons.get(c);
            } else {
                return false;
            }
        }
        
        return node.end;
    }
}

public class Solution {
    private int[] dx = {1, 0, -1, 0};
    private int[] dy = {0, 1, 0, -1};
    private Trie t;
    
    public List<String> findWords(char[][] board, String[] words) {
        List<String> result = new ArrayList<>();
        
        t = new Trie();
        for (String word: words) {
            t.insert(word);
        }
        
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                search(board, i, j, t.root, result);
            }
        }
        return result;
    }
    
    public void search(char[][] board, int x, int y, TrieNode node, List<String> result) {
        if (node.end) {
            if (!result.contains(node.s)) {
                result.add(node.s);
            }
        }
        if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || board[x][y] == 0 || node == null) return;
        if (node.sons.containsKey(board[x][y])) {
            for (int i = 0; i < 4; i++) {
                char c = board[x][y];
                board[x][y] = 0;
                search(board, x + dx[i], y + dy[i], node.sons.get(c), result);
                board[x][y] = c;
            }
        }
    }
}

Solution

用字典樹實(shí)現(xiàn)。講所有字符串加進(jìn)字典樹。DFS遍歷board廉赔,將符合條件的字符串加入結(jié)果集中衅鹿。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖锣披,帶你破解...
    沈念sama閱讀 217,084評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異贿条,居然都是意外死亡雹仿,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評論 3 392
  • 文/潘曉璐 我一進(jìn)店門整以,熙熙樓的掌柜王于貴愁眉苦臉地迎上來胧辽,“玉大人,你說我怎么就攤上這事公黑∫厣蹋” “怎么了摄咆?”我有些...
    開封第一講書人閱讀 163,450評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長人断。 經(jīng)常有香客問我吭从,道長,這世上最難降的妖魔是什么恶迈? 我笑而不...
    開封第一講書人閱讀 58,322評論 1 293
  • 正文 為了忘掉前任涩金,我火速辦了婚禮,結(jié)果婚禮上蝉绷,老公的妹妹穿的比我還像新娘鸭廷。我一直安慰自己,他們只是感情好熔吗,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,370評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著佳晶,像睡著了一般桅狠。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上轿秧,一...
    開封第一講書人閱讀 51,274評論 1 300
  • 那天中跌,我揣著相機(jī)與錄音,去河邊找鬼菇篡。 笑死漩符,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的驱还。 我是一名探鬼主播嗜暴,決...
    沈念sama閱讀 40,126評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼议蟆!你這毒婦竟也來了闷沥?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,980評論 0 275
  • 序言:老撾萬榮一對情侶失蹤咐容,失蹤者是張志新(化名)和其女友劉穎舆逃,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體戳粒,經(jīng)...
    沈念sama閱讀 45,414評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡路狮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,599評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蔚约。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片奄妨。...
    茶點(diǎn)故事閱讀 39,773評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖炊琉,靈堂內(nèi)的尸體忽然破棺而出展蒂,到底是詐尸還是另有隱情又活,我是刑警寧澤,帶...
    沈念sama閱讀 35,470評論 5 344
  • 正文 年R本政府宣布锰悼,位于F島的核電站柳骄,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏箕般。R本人自食惡果不足惜耐薯,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,080評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望丝里。 院中可真熱鬧曲初,春花似錦、人聲如沸杯聚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽幌绍。三九已至颁褂,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間傀广,已是汗流浹背颁独。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留伪冰,地道東北人誓酒。 一個(gè)月前我還...
    沈念sama閱讀 47,865評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像贮聂,于是被迫代替她去往敵國和親靠柑。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,689評論 2 354

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