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? = ""
}
}