LeetCode-212 单词搜索 II

原题:

 

class Solution {

    //构建前缀树 + dfs  深度遍历字符数组,然后和前缀树比较 
 


    //定义节点
    static class TireNode{
       
        //使用map 还是 数组
        Map<Character,TireNode> childNode;
        boolean isEnd = false;
        public TireNode(){
            childNode = new  HashMap<Character,TireNode>();
        }
    }

  
        private  static void addWord(String word)
        {
            TireNode curnode = node;
            char[] letter = word.toCharArray();
            for(int i = 0 ; i < letter.length ; i++)
            {
                char cur = letter[i];
                if(!curnode.childNode.containsKey(cur))
                {
                    curnode.childNode.put(cur , new TireNode());
                }
                curnode = curnode.childNode.get(cur); //指向子节点
            }
            curnode.isEnd = true;
            
        }

       boolean[][] flag;

       Set<String> res;

       static TireNode node ;
        
       int[][] directions = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; //代表4个方向的偏移量

    public List<String> findWords(char[][] board, String[] words) {
            //前缀树 + dfs
            int rows = board.length;
            int cols = board[0].length;
            flag = new boolean[rows][cols];
            res = new HashSet<>();
            node = new TireNode();
            for(String s : words)
            {
                addWord(s);//构建字典树
            }

            for(int i = 0 ; i < rows ; i++)
            {
                for(int j = 0 ; j < cols ; j++)
                {
                       
                     StringBuffer cur = new StringBuffer();
                     dfs(board,i,j,node,cur);  

                }
            }
        List<String> list = new ArrayList<>(res);
      
            return list;

    }

    private void dfs(char[][] board, int i , int j,TireNode node , StringBuffer cur)
    {
         if(node.isEnd)
        {
            res.add(cur.toString());
           
             }
          
        //边界条件 结束条件
        if(i < 0 || j < 0 || i >= board.length || j >= board[0].length || flag[i][j])return ;
       
       

        if(node.childNode.containsKey(board[i][j]))
        {
            cur.append(board[i][j]);
            flag[i][j] = true;
           
            for(int k = 0 ; k < 4 ; k++)
             {
             
             int newx = i + directions[k][0];
             int newy = j + directions[k][1];
            
             dfs(board,newx,newy,node.childNode.get(board[i][j]),cur);
            
            }

        cur.deleteCharAt(cur.length() - 1);//状态恢复
        flag[i][j] = false;
       
        }
        
        

    }
}

 

posted @ 2020-05-07 21:18  贼心~不死  阅读(142)  评论(0编辑  收藏  举报