[leetcode 单词搜索]-[trie树]

解法:
trie树

import java.util.*;

class Solution {
    int m, n;
    char[][] board;

    String[] querys;

    public static void main(String[] args) {
        Solution solution = new Solution();
        List<String> list = solution.findWords(new char[][]{
                {'o', 'a', 'a', 'n'}, {'e', 't', 'a', 'e'}, {'i', 'h', 'k', 'r'}, {'i', 'f', 'l', 'v'}
        }, new String[]{
                "oath", "pea", "eat", "rain"
        });

        for (String str : list) {
            System.out.println(str);
        }
    }

    Set<String> set = new TreeSet<>();

    public List<String> findWords(char[][] board, String[] words) {
        m = board.length;
        n = board[0].length;

        this.board = board;
        this.querys = words;

        int idx = 0;
        for (String word : words) {
            buildTree(word, idx++);
        }


        for (int x = 0; x < m; x++) {
            for (int y = 0; y < n; y++) {

                boolean[][] traved = new boolean[m][n];
                dfs(x, y, 1, traved, root);
            }
        }
//        return list.stream().map(STR::getStr).collect(Collectors.toList());
        return new ArrayList<>(set);
    }

    Node root;

    class Node {
        Node parent;
        Node[] children = new Node[26];
        int existIndex = -1;

        public Node() {
        }

        public Node(Node parent) {
            this.parent = parent;
        }
    }

    public void buildTree(String str, int index) {
        if (root == null) {
            root = new Node();
        }
        Node curr = root;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            Node child = curr.children[ch - 'a'];
            if (child == null) {
                curr.children[ch - 'a'] = new Node(curr);
            }
            if (i == str.length() - 1) {
                curr.children[ch - 'a'].existIndex = index;
            }
            curr = curr.children[ch - 'a'];
        }
    }

    public void dfs(int x, int y, int step,boolean[][] traved, Node parent) {
        Node curr = parent.children[board[x][y] - 'a'];
        if (curr == null) {
            return;
        }

        if (curr.existIndex > -1) {
            set.add(querys[curr.existIndex]);
        }

        traved[x][y] = true;

        int[][] dir = new int[][]{
                {1, 0}, {-1, 0},
                {0, 1}, {0, -1}
        };

        for (int i = 0; i < 4; i++) {
            int newx = x + dir[i][0];
            int newy = y + dir[i][1];

            if (newx >= 0 && newx < m && newy >= 0 && newy < n && !traved[newx][newy]) {
                traved[newx][newy] = true;
                dfs(newx, newy, step+1,traved, curr);
                traved[newx][newy] = false;
            }
        }
        traved[x][y] = false;
    }
}```
posted @ 2024-04-06 15:31  fishcanfly  阅读(19)  评论(0)    收藏  举报
//雪花飘落效果