|
| 1 | +/** |
| 2 | + * 2018. Check if Word Can Be Placed In Crossword |
| 3 | + * https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an m x n matrix board, representing the current state of a crossword puzzle. |
| 7 | + * The crossword contains lowercase English letters (from solved words), ' ' to represent any |
| 8 | + * empty cells, and '#' to represent any blocked cells. |
| 9 | + * |
| 10 | + * A word can be placed horizontally (left to right or right to left) or vertically (top to |
| 11 | + * bottom or bottom to top) in the board if: |
| 12 | + * - It does not occupy a cell containing the character '#'. |
| 13 | + * - The cell each letter is placed in must either be ' ' (empty) or match the letter already |
| 14 | + * on the board. |
| 15 | + * - There must not be any empty cells ' ' or other lowercase letters directly left or right |
| 16 | + * of the word if the word was placed horizontally. |
| 17 | + * - There must not be any empty cells ' ' or other lowercase letters directly above or below |
| 18 | + * the word if the word was placed vertically. |
| 19 | + * |
| 20 | + * Given a string word, return true if word can be placed in board, or false otherwise. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {character[][]} board |
| 25 | + * @param {string} word |
| 26 | + * @return {boolean} |
| 27 | + */ |
| 28 | +var placeWordInCrossword = function(board, word) { |
| 29 | + const rows = board.length; |
| 30 | + const cols = board[0].length; |
| 31 | + const wordLen = word.length; |
| 32 | + |
| 33 | + function canPlace(row, col, dr, dc) { |
| 34 | + for (let i = 0; i < wordLen; i++) { |
| 35 | + const r = row + i * dr; |
| 36 | + const c = col + i * dc; |
| 37 | + if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] === '#') return false; |
| 38 | + if (board[r][c] !== ' ' && board[r][c] !== word[i]) return false; |
| 39 | + } |
| 40 | + |
| 41 | + const beforeR = row - dr; |
| 42 | + const beforeC = col - dc; |
| 43 | + const afterR = row + wordLen * dr; |
| 44 | + const afterC = col + wordLen * dc; |
| 45 | + |
| 46 | + if ((beforeR >= 0 && beforeR < rows && beforeC >= 0 |
| 47 | + && beforeC < cols && board[beforeR][beforeC] !== '#') |
| 48 | + || (afterR >= 0 && afterR < rows && afterC >= 0 |
| 49 | + && afterC < cols && board[afterR][afterC] !== '#')) { |
| 50 | + return false; |
| 51 | + } |
| 52 | + |
| 53 | + return true; |
| 54 | + } |
| 55 | + |
| 56 | + for (let r = 0; r < rows; r++) { |
| 57 | + for (let c = 0; c < cols; c++) { |
| 58 | + if (canPlace(r, c, 0, 1) || canPlace(r, c, 0, -1) |
| 59 | + || canPlace(r, c, 1, 0) || canPlace(r, c, -1, 0)) { |
| 60 | + return true; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return false; |
| 66 | +}; |
0 commit comments