212. Word Search II

复制代码
package LeetCode_212

/**
 * 212. Word Search II
 * https://leetcode.com/problems/word-search-ii/
 * Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring.
The same letter cell may not be used more than once in a word.
Example 1:
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"]

Constraints:
1. m == board.length
2. n == board[i].length
3. 1 <= m, n <= 12
4. board[i][j] is a lowercase English letter.
5. 1 <= words.length <= 3 * 104
6. 1 <= words[i].length <= 10
7. words[i] consists of lowercase English letters.
8. All the strings of words are unique.
 * */
class Solution {
    /*
    * solution: TrieTree + DFS, save all word into Trie, search the board by DFS;
    * Time: O(m*n*4^l), l is length of word, because each letter has 4 path to check
    * Space: O(m*n)
    * */

    var root: TrieNode? = null

    init {
        root = TrieNode()
    }

    fun findWords(board: Array<CharArray>, words: Array<String>): List<String> {
        createTree(words)
        val result = ArrayList<String>()
        val m = board.size
        val n = board[0].size
        val visited = Array(m){BooleanArray(n)}
        for (i in 0 until m) {
            for (j in 0 until n) {
                dfs(board, i, j, "", result, visited)
            }
        }
        return result
    }

    private fun dfs(board: Array<CharArray>, x: Int, y: Int, s:String, result: ArrayList<String>, visited:Array<BooleanArray>) {
        if (x < 0 || x >= board.size || y < 0 || y >= board[0].size || visited[x][y]) {
            return
        }
        var cur = s
        cur += board[x][y]
        if (!startWith(cur)) {
            return
        }
        if (search(cur)) {
            //avoid duplicate
            if (!result.contains(cur)) {
                result.add(cur)
            }
        }
        visited[x][y] = true
        //search 4 directions
        dfs(board, x + 1, y, cur, result, visited)
        dfs(board, x - 1, y, cur, result, visited)
        dfs(board, x, y + 1, cur, result, visited)
        dfs(board, x, y - 1, cur, result, visited)
        //set back for next level, let it can go through again
        visited[x][y] = false
    }

    private fun startWith(word: String): Boolean {
        val node = find(word)
        if (node == null) {
            return false
        }
        return true
    }

    private fun search(word: String): Boolean {
        val node = find(word)
        if (node == null) {
            return false
        }
        return node.word.equals(word)
    }

    private fun find(word: String): TrieNode? {
        var cur = root
        for (c in word) {
            val index = c - 'a'
            if (cur!!.children[index] == null) {
                return null
            }
            cur = cur!!.children[index]
        }
        return cur
    }

    //create tree by word
    private fun createTree(words: Array<String>) {
        for (word in words) {
            var current = root
            for (c in word) {
                val index = c - 'a'
                if (current!!.children[index] == null) {
                    current.children[index] = TrieNode()
                }
                current = current.children[index]!!
            }
            //make last node as leaf
            current!!.word = word
        }
    }

    class TrieNode {
        var children = arrayOfNulls<TrieNode>(26)
        var word: String? = ""
    }
}
复制代码

 

posted @   johnny_zhao  阅读(132)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-01-01 965. Univalued Binary Tree
2019-01-01 369. Plus One Linked List
2019-01-01 143. Reorder List
2019-01-01 94. Binary Tree Inorder Traversal
2019-01-01 144. Binary Tree Preorder Traversal
2019-01-01 145. Binary Tree Postorder Traversal
点击右上角即可分享
微信分享提示