Leetcode 212. Word Search II

不要背诵代码,要尝试理解代码。

万变不离其宗。


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值