212. Word Search II

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.

 

Example:

Input: 
board = [
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
words = ["oath","pea","eat","rain"]

Output: ["eat","oath"]
 

Note:

All inputs are consist of lowercase letters a-z.
The values of words are distinct.

很明显这题需要使用DFS,下面为自己不熟练DFS代码。

PS:后面还有看了discuss之后的超级优化版本。

个人版代码:

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

    public List<String> findWords(char[][] board, String[] words) {
        List<String> ans = new ArrayList<>();
        if(board.length == 0) return ans;
        boolean[][] visited = new boolean[board.length][board[0].length];
        Map<Character, List<Pair<Integer, Integer>>> map = new HashMap<>();
        for(int i = 0; i < board.length; ++i) {
            for(int j = 0; j < board[0].length; ++j) {
                List<Pair<Integer, Integer>> tempList = map.getOrDefault(board[i][j], new ArrayList<>());
                tempList.add(new Pair<>(i, j));
                map.put(board[i][j], tempList);
            }
        }
        for(String word : words) {
            if(word.length() > 0 && map.containsKey(word.charAt(0))) {
                List<Pair<Integer, Integer>> tempList = map.get(word.charAt(0));
                for(Pair<Integer, Integer> pair : tempList) {
                    if(dfs(pair.getKey(), pair.getValue(), word, 0, board, visited)) {
                        ans.add(word);
                        break;
                    }
                }
            }
        }
        return ans;
    }

    private boolean dfs(int i, int j, String word, int n, char[][] board, boolean[][] visited) {
        if(visited[i][j])
            return false;
        else
            visited[i][j] = true;
        if(n == word.length() - 1) {
            visited[i][j] = false;
            return true;
        }
        n++;
        for(int k = 0; k < 4; ++k) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(n < word.length() && 0 <= x && x < board.length && 0 <= y && y <board[0].length && board[x][y] == word.charAt(n)) {
                if(dfs(x, y, word, n, board, visited)){
                    visited[i][j] = false;
                    return true;
                }
            }
        }
        visited[i][j] = false;
        return false;
    }

超级优化版代码如下。可以先对比一下运行速度:

能优化这么多,个人认为全是因为前缀树的加入比使用Map来存储要快很多。

class TrieNode {
        TrieNode[] next = new TrieNode[26];
        String word;
    }

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

    public TrieNode buildTrie(String[] word) {
        TrieNode root = new TrieNode();
        for(String str : word) {
            TrieNode node = root;
            for(char ch : str.toCharArray()) {
                int i = ch - 'a';
                if(node.next[i] == null) {
                    node.next[i] = new TrieNode();
                }
                node = node.next[i];
            }
            node.word = str;
        }
        return root;
    }

    public List<String> findWords(char[][] board, String[] words) {
        List<String> ans = new ArrayList<>();
        TrieNode root = buildTrie(words);
        for(int i = 0; i < board.length; ++i) {
            for(int j = 0; j < board[0].length; ++j) {
                dfs(board, i, j, root, ans);
            }
        }
        return ans;
    }

    private void dfs(char[][] board, int i, int j, TrieNode p, List<String> ans) {
        char ch = board[i][j];
        if(ch == '#' || p.next[ch-'a'] == null) {
            return;
        }
        p = p.next[ch-'a'];
        if(p.word != null) {
            ans.add(p.word);
            p.word = null;
        }
        board[i][j] = '#';
        for(int k = 0; k < 4; ++k) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(0 <= x && x < board.length && 0 <= y & y < board[0].length) {
                dfs(board, x, y, p, ans);
            }
        }
        board[i][j] = ch;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值