LeetCode 212 Word Search II (Trie树+DFS)

本文提供了一种解决LeetCode上单词搜索II问题的方法,通过构建Trie树并使用深度优先搜索策略来查找给定二维字符网格中存在的所有字典词汇。

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

Note:

You may assume that all inputs are consist of lowercase letters a-z.

题目链接:https://leetcode.com/problems/word-search-ii/

题目分析:先按给定的单词建立Trie树,然后从矩阵中的每个单词的首字母开始深搜,深搜的要按照字典树中单词的方向,注意找到一个后不能直接return,因为可能存在某个单词是另一个单词的前缀。

击败了63%

public class Solution {
    
    public static final int dx[] = {1, 0, -1, 0};
    public static final int dy[] = {0, 1, 0, -1};
    
    public boolean[][] vis;
    
    class Trie {
        boolean end;
        String word;
        Trie[] nxt;
        
        public Trie() {
            nxt = new Trie[26];
            end = false;
            word = "";
            for (int i = 0; i < 26; i ++) {
                nxt[i] = null;
            }
        }
        
        public void Insert(Trie root, String str) {
            int len = str.length();
            Trie p = root;
            for (int i = 0; i < len; i ++) {
                int idx = str.charAt(i) - 'a';
                if (p.nxt[idx] == null) {
                    p.nxt[idx] = new Trie();
                }
                p = p.nxt[idx];
            }
            p.end = true;
            p.word = str;
        }
    }
    
    public void DFS(int x, int y, int n, int m, Trie cur, boolean[][] vis, char[][] board, List<String> ans) {
        if (cur == null) {
            return;
        }
        if (cur.end) {
            cur.end = false;
            ans.add(cur.word);
        }
        for (int i = 0; i < 4; i ++) {
            int xx = x + dx[i];
            int yy = y + dy[i];
            if (xx >= 0 && yy >= 0 && xx < n && yy < m && !vis[xx][yy]) {
                int idx = board[xx][yy] - 'a';
                if (cur.nxt[idx] != null) {
                    vis[xx][yy] = true;
                    DFS(xx, yy, n, m, cur.nxt[idx], vis, board, ans);
                    vis[xx][yy] = false;
                }
            } 
        }
        return;
    }
    
    public List<String> findWords(char[][] board, String[] words) {
        Trie root = new Trie();
        for (int i = 0; i < words.length; i ++) {
            root.Insert(root, words[i]);
        }
        List<String> ans = new ArrayList<>();
        int n = board.length;
        if (n == 0) {
            return ans;
        }
        int m = board[0].length;
        vis = new boolean[n][m];
        for (int i = 0; i < n; i ++) {
            for (int j = 0; j < m; j ++) {               
                int idx = board[i][j] - 'a';
                if (root.nxt[idx] != null) {
                    vis[i][j] = true;
                    DFS(i, j, n, m, root.nxt[idx], vis, board, ans);
                    vis[i][j] = false;
                }
            }
        }
        // Collections.sort(ans, new Comparator() {
        //     @Override
        //     public int compare(Object o1, Object o2) {
        //         return ((String) o1).compareTo((String) o2);
                
        //     }
        // });
        return ans;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值