|
| 1 | +/** |
| 2 | + * Question Link: https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/ |
| 3 | + * Primary idea: Classic Depth-first Search, check possible position and go through four directions |
| 4 | + * |
| 5 | + * Time Complexity: O(mnl), Space Complexity: O(1) |
| 6 | + * |
| 7 | + */ |
| 8 | + |
| 9 | +class CheckWordCrossword { |
| 10 | + func placeWordInCrossword(_ board: [[Character]], _ word: String) -> Bool { |
| 11 | + let dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)], m = board.count, n = board[0].count |
| 12 | + |
| 13 | + for i in 0..<m { |
| 14 | + for j in 0..<n { |
| 15 | + for dir in dirs { |
| 16 | + let prev = (i - dir.0, j - dir.1) |
| 17 | + |
| 18 | + guard !isValid(prev.0, prev.1, board) else { |
| 19 | + continue |
| 20 | + } |
| 21 | + |
| 22 | + if dfs(0, Array(word), board, i, j, dir) { |
| 23 | + return true |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + return false |
| 31 | + } |
| 32 | + |
| 33 | + private func isValid(_ i: Int, _ j: Int, _ board: [[Character]]) -> Bool { |
| 34 | + let m = board.count, n = board[0].count |
| 35 | + |
| 36 | + return i >= 0 && i < m && j >= 0 && j < n && board[i][j] != "#" |
| 37 | + } |
| 38 | + |
| 39 | + private func dfs(_ idx: Int, _ word: [Character], _ board: [[Character]], _ i: Int, _ j: Int, _ dir: (Int, Int)) -> Bool { |
| 40 | + if idx == word.count { |
| 41 | + return !isValid(i, j, board) |
| 42 | + } |
| 43 | + |
| 44 | + guard isValid(i, j, board) else { |
| 45 | + return false |
| 46 | + } |
| 47 | + |
| 48 | + guard board[i][j] == " " || board[i][j] == word[idx] else { |
| 49 | + return false |
| 50 | + } |
| 51 | + |
| 52 | + return dfs(idx + 1, word, board, i + dir.0, j + dir.1, dir) |
| 53 | + } |
| 54 | +} |
0 commit comments