| 31 | } |
| 32 | |
| 33 | fun dfs(board: Array<CharArray>, r: Int, c: Int, node: TrieNode?, res: MutableList<String>) { |
| 34 | // If the current node represents the end of a word, add the word to |
| 35 | // the result. |
| 36 | if (node?.word != null) { |
| 37 | res.add(node.word!!) |
| 38 | // Ensure the current word is only added once. |
| 39 | node.word = null |
| 40 | } |
| 41 | val temp = board[r][c] |
| 42 | // Mark the current cell as visited. |
| 43 | board[r][c] = '#' |
| 44 | // Explore all adjacent cells that correspond with a child of the |
| 45 | // current TrieNode. |
| 46 | val dirs = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) |
| 47 | for ((dr, dc) in dirs) { |
| 48 | val nextR = r + dr |
| 49 | val nextC = c + dc |
| 50 | if (isWithinBounds(board, nextR, nextC) && board[nextR][nextC] in node?.children.orEmpty()) { |
| 51 | dfs(board, nextR, nextC, node?.children?.get(board[nextR][nextC]), res) |
| 52 | } |
| 53 | // Backtrack by reverting the cell back to its original character. |
| 54 | board[r][c] = temp |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | fun isWithinBounds(board: Array<CharArray>, r: Int, c: Int): Boolean { |
| 59 | return r in board.indices && c in board[0].indices |
no test coverage detected