Leetcode-79. 单词搜索

给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.

解法:dfs回溯,加上使用数组记录走过的位置,时间复杂度O(N)

  • Java
class Solution {
   
    public boolean exist(char[][] board, String word) {
   
        if (word==null) return true;
        boolean[][] visited = new boolean[board.length][board[0].length];
        for (int i=0;i<board.length;i++) {
   
            for (int j=0;j<board[0].length;j++) {
   
                if (board[i][j]==word.charAt(0) && this.search(board, word, i, j, 0, visited)) {
   
                    return true;
                }
            }
        }
        return false;
    }
    public boolean search(char[][] board, String word, int i, int j, int index, boolean[][] visited) {
   
        if (index>=word.length()) return true;
        if (i<0 || i>=board.length || j<0 || j>=board[0].length || board[i][j]!=word.charAt(index) || visited[i][j]) {
   
            return false;
        }
        visited[i][j] = true;
        if (this.search(board,word,i-1,j,index+1,visited) ||
           this.search(board,word,i,j+1,index+1,visited) ||
           this.search(board,word,i+1,j,index+1,visited) ||
           this.search(board,word,i,j-1,index+1,visited) )
            return true;
        visited[i][j] = false;
        return false;
    }
}
  • Python
class Solution:
    def exist(self, board, word):
        if not board:
            return False
        for i in range(len(board)):
            for j in range(len(board[0])):
                if self.dfs(board, i, j, word):
                    return True
        return False

    # check whether can find word, start at (i,j) position 
    def dfs(self, board, i, j, word):
        if len(word) == 0: # all the characters are checked
            return True
        if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]:
            return False
        tmp = board[i][j]  # first character is found, check the remaining part
        board[i][j] = "#"  # avoid visit agian 
        # check whether can find "word" along one direction
        res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) \
        or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:])
        board[i][j] = tmp
        return res

Leetcode-212. 单词搜索 II

给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。

示例:

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

输出: ["eat","oath"]

说明:
你可以假设所有输入都由小写字母 a-z 组成。

提示:

  • 你需要优化回溯算法以通过更大数据量的测试。你能否早点停止回溯?
  • 如果当前单词不存在于所有单词的前缀中,则可以立即停止回溯。什么样的数据结构可以有效地执行这样的操作?散列表是否可行?为什么? 前缀树如何?如果你想学习如何实现一个基本的前缀树,请先查看这个问题: 实现Trie(前缀树)。

解法:1. 与上题同解法,使用dfs。2. 使用Trie,先把所有字符放在Trie中

  • Java
    dfs
class Solution {
   
    public List<String> findWords(char[][] board, String[] words) {
   
        List<String> res = new ArrayList<>();
        for (String word:words) {
   
            if (this.exist(board,word)) {
   
                res.add(word);
            }
        }
        return res;
    }
    public boolean exist(char[][] board, String word) {
   
        if (word==null) return true;
        boolean[][] visited = new boolean[board.length][board[0].length];
        for (int i=0;i<board.length;i++) {
   
            for (int j=0;j<board[0].length;j++) {
   
                if (board[i][j]==word.charAt(0) && this.search(board, word, i, j, 0, visited)) {
   
                    return true;
                }
            }
        }
        return false;
    }
    public boolean search(char[][] board, String word, int i, int j, int index, boolean[][] visited) {
   
        if (index>=word.length()) return true;
        if (i<0 || i>=board.length || j<0 || j>=board[0].length || board[i][j]!=word.charAt(index) || visited[i][j]) {
   
            return false;
        }
        visited[i][j] = true;
        if (this.search(board,word,i-1,j,index+1,visited) ||
           this.search(board,word,i,j+1,index+1,visited) ||
           this.search(board,word,i+1,j,index+1,visited) ||
           this.search(board,word,i,j-1,index+1,visited) )
            return true;
        visited[i][j] = false;
        return false;
    }
}

Trie+dfs,先按照上一节中的代码建立Trie树,在往里添加,区别就在于比较word的方式,一个是一位一位的比,一个是放在树里面用前缀来比。

class TrieNode {
   
    public char val;
    public TrieNode[] children = new TrieNode[26];
    public boolean isWord;
    public TrieNode(char c) {
   
        this.val = c;
    }
}
class Trie {
   
    public TrieNode root = new TrieNode(' ');
    public void insert(String word) {
   
        TrieNode node = root;
        for (int i=0;i<word.length();i++) {
   
            char c = word.charAt(i);
            if (node.children[c-'a']==null) {
   
                node.children[c-'a'] = new TrieNode(c);
            }
            node = node.children[c-'a'];
        }
        node.isWord = true;
    }
    public boolean search(String word) {
   
        TrieNode node = root;
        for (int i=0;i<word.length();i++) {
   
            char c = word.charAt(i);
            if (node.children[c-'a']==null) return false;
            node = node.children[c-'a'];
        }
        return node.isWord;
    }
    public boolean startsWith(String prefix) {
   
        TrieNode node = root;
        for (int i=0;i<prefix.length();i++) {
   
            char c = prefix.charAt(i);
            if (node.children[c-'a']==null) return false;
            node = node.children[c-'a'];
        }
        return true;
    }
}
class Solution {
   
    public Set<String> set = new HashSet<>();
    public List<String> findWords(char[][] board, String[] words) {
   
        Trie trie = new Trie();
        for (String word:words) {
   
            trie.insert(word);
        }
        int m = board.length, n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for (int i=0;i<m;i++) {
   
            for (int j=0;j<n;j++) {
   
                this.dfs(board, visited, i, j, "", trie);
            }
        }
        return new ArrayList<String>(set);
    }
    public void dfs(char[][] board, boolean[][] visited, int i, int j, String str, Trie trie) {
   
        if (i<0 || i>=board.length || j<0 || j>=board[0].length || visited[i][j]) 
            return;
        str += board[i][j];
        if (!trie.startsWith(str)) 
            return;
        if (trie.search(str)) {
   
            this.set.add(str);
            // return; // 这里不应该return,例如aaa,如果还有aaab本来也能找到,但以aaa为前缀,aaa已经return了,这个就不会被添加
        }
        visited[i][j] = true;
        this.dfs(board, visited, i-1, j, str, trie);
        this.dfs(board, visited, i, j+1, str, trie);
        this.dfs(board, visited, i+1, j, str, trie);
        this.dfs(board, visited, i, j-1, str, trie);
        visited[i][j] = false;
    }
}
  • Python
class TrieNode():
    def __init__(self):
        self.children = collections.defaultdict(TrieNode)
        self.isWord = False
    
class Trie():
    def __init__(self):
        self.root = TrieNode()
    
    def insert(self, word):
        node = self.root
        for w in word:
            node = node.children[w]
        node.isWord = True
    
    def search(self, word):
        node = self.root
        for w in word:
            node = node.children.get(w)
            if not node:
                return False
        return node.isWord
    
class Solution(object):
    def findWords(self, board, words):
        res = []
        trie = Trie()
        node = trie.root
        for w in words:
            trie.insert(w)
        for i in range(len(board)):
            for j in range(len(board[0])):
                self.dfs(board, node, i, j, "", res)
        return res
    
    def dfs(self, board, node, i, j, path, res):
        if node.isWord:
            res.append(path)
            node.isWord = False
        if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
            return 
        tmp = board[i][j]
        node = node.children.get(tmp)
        if not node:
            return 
        board[i][j] = "#"
        self.dfs(board, node, i+1, j, path+tmp, res)
        self.dfs(board, node, i-1, j, path+tmp, res)
        self.dfs(board, node, i, j-1, path+tmp, res)
        self.dfs(board, node, i, j+1, path+tmp, res)
        board[i][j] = tmp