|
| 1 | +/** |
| 2 | + * Question Link: https://leetcode.com/problems/word-search-ii/ |
| 3 | + */ |
| 4 | + |
| 5 | +class Solution { |
| 6 | + class TrieNode { |
| 7 | + var children = [Character: TrieNode]() |
| 8 | + var word: String = "" |
| 9 | + } |
| 10 | + |
| 11 | + func findWords(_ board: [[Character]], _ words: [String]) -> [String] { |
| 12 | + var answer = [String]() |
| 13 | + let root = buildTrie(words) |
| 14 | + |
| 15 | + var board = board |
| 16 | + |
| 17 | + for row in 0..<board.count { |
| 18 | + for col in 0..<board[0].count { |
| 19 | + if root.children[board[row][col]] != nil { |
| 20 | + dfs(row, col, root,&board,&answer) |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + return answer |
| 26 | + } |
| 27 | + |
| 28 | + func buildTrie(_ words: [String]) -> TrieNode { |
| 29 | + let root = TrieNode() |
| 30 | + for word in words { |
| 31 | + var current = root |
| 32 | + |
| 33 | + word.forEach { |
| 34 | + if current.children[$0] == nil { |
| 35 | + current.children[$0] = TrieNode() |
| 36 | + } |
| 37 | + current = current.children[$0]! |
| 38 | + } |
| 39 | + current.word = word |
| 40 | + } |
| 41 | + |
| 42 | + return root |
| 43 | + } |
| 44 | + |
| 45 | + func getInBoardChild(_ x: Int, _ y: Int,_ board:[[Character]],_ root: TrieNode) -> TrieNode? { |
| 46 | + if 0..<board[0].count ~= x && 0..<board.count ~= y && board[y][x] != "." { |
| 47 | + return root.children[board[y][x]] |
| 48 | + } |
| 49 | + return nil |
| 50 | + } |
| 51 | + |
| 52 | + func dfs( _ y: Int,_ x: Int,_ root: TrieNode,_ board: inout [[Character]],_ answer: inout [String]) { |
| 53 | + guard let child = getInBoardChild(x, y, board, root) else { return } |
| 54 | + |
| 55 | + let char = board[y][x] |
| 56 | + board[y][x] = "." |
| 57 | + |
| 58 | + if !child.word.isEmpty { |
| 59 | + answer.append(child.word) |
| 60 | + child.word = "" |
| 61 | + } |
| 62 | + |
| 63 | + for d in [(x-1,y),(x+1,y),(x,y-1),(x,y+1)] { |
| 64 | + dfs(d.1,d.0, child,&board,&answer) |
| 65 | + } |
| 66 | + |
| 67 | + board[y][x] = char |
| 68 | + } |
| 69 | +} |
0 commit comments