2018. Check if Word Can Be Placed In Crossword
Description
You are given an m x n
matrix board
, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' '
to represent any empty cells, and '#'
to represent any blocked cells.
A word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:
- It does not occupy a cell containing the character
'#'
. - The cell each letter is placed in must either be
' '
(empty) or match the letter already on theboard
. - There must not be any empty cells
' '
or other lowercase letters directly left or rightof the word if the word was placed horizontally. - There must not be any empty cells
' '
or other lowercase letters directly above or below the word if the word was placed vertically.
Given a string word
, return true
if word
can be placed in board
, or false
otherwise.
Example 1:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", "c", " "]], word = "abc" Output: true Explanation: The word "abc" can be placed as shown above (top to bottom).
Example 2:
Input: board = [[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac" Output: false Explanation: It is impossible to place the word because there will always be a space/letter above or below it.
Example 3:
Input: board = [["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca" Output: true Explanation: The word "ca" can be placed as shown above (right to left).
Constraints:
m == board.length
n == board[i].length
1 <= m * n <= 2 * 105
board[i][j]
will be' '
,'#'
, or a lowercase English letter.1 <= word.length <= max(m, n)
word
will contain only lowercase English letters.
Solutions
Solution: Simulation
- Time complexity: O(mn)
- Space complexity: O(mn)
JavaScript
js
/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
const placeWordInCrossword = function (board, word) {
const m = board.length;
const n = board[0].length;
const isCorner = cell => cell === '#' || cell === undefined;
const isCanPlaced = (row, col, moveX, moveY) => {
for (const element of word) {
const letter = board[row]?.[col];
if (letter !== element && letter !== ' ') return false;
row += moveY;
col += moveX;
}
return isCorner(board[row]?.[col]);
};
for (let row = 0; row < m; row++) {
for (let col = 0; col < n; col++) {
if (isCorner(board[row][col])) continue;
const leftCell = board[row][col - 1];
const rightCell = board[row][col + 1];
const aboveCell = board[row - 1]?.[col];
const bellowCell = board[row + 1]?.[col];
if (isCorner(leftCell) && isCanPlaced(row, col, 1, 0)) return true;
if (isCorner(rightCell) && isCanPlaced(row, col, -1, 0)) return true;
if (isCorner(aboveCell) && isCanPlaced(row, col, 0, 1)) return true;
if (isCorner(bellowCell) && isCanPlaced(row, col, 0, -1)) return true;
}
}
return false;
};