From 3876ad42383d8f4f0edf01d53c4698e8b9970b5e Mon Sep 17 00:00:00 2001 From: Soap Date: Sat, 1 Oct 2022 22:37:29 -0700 Subject: [PATCH] Add a solution to Check if Word Can Be Placed In Crossword --- DFS/CheckWordCrossword.swift | 54 ++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 DFS/CheckWordCrossword.swift diff --git a/DFS/CheckWordCrossword.swift b/DFS/CheckWordCrossword.swift new file mode 100644 index 0000000..9439696 --- /dev/null +++ b/DFS/CheckWordCrossword.swift @@ -0,0 +1,54 @@ +/** + * Question Link: https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/ + * Primary idea: Classic Depth-first Search, check possible position and go through four directions + * + * Time Complexity: O(mnl), Space Complexity: O(1) + * + */ + +class CheckWordCrossword { + func placeWordInCrossword(_ board: [[Character]], _ word: String) -> Bool { + let dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)], m = board.count, n = board[0].count + + for i in 0.. Bool { + let m = board.count, n = board[0].count + + return i >= 0 && i < m && j >= 0 && j < n && board[i][j] != "#" + } + + private func dfs(_ idx: Int, _ word: [Character], _ board: [[Character]], _ i: Int, _ j: Int, _ dir: (Int, Int)) -> Bool { + if idx == word.count { + return !isValid(i, j, board) + } + + guard isValid(i, j, board) else { + return false + } + + guard board[i][j] == " " || board[i][j] == word[idx] else { + return false + } + + return dfs(idx + 1, word, board, i + dir.0, j + dir.1, dir) + } +}