LeetCode 2018. Check if Word Can Be Placed In Crossword【数组/枚举/DFS】中等

本文属于「征服LeetCode」系列文章之一,这一系列正式开始于2021/08/12。由于LeetCode上部分题目有锁,本系列将至少持续到刷完所有无锁题之日为止;由于LeetCode还在不断地创建新题,本系列的终止日期可能是永远。在这一系列刷题文章中,我不仅会讲解多种解题思路及其优化,还会用多种编程语言实现题解,涉及到通用解法时更将归纳总结出相应的算法模板。

为了方便在PC上运行调试、分享代码文件,我还建立了相关的仓库:https://github.com/memcpy0/LeetCode-Conquest。在这一仓库中,你不仅可以看到LeetCode原题链接、题解代码、题解文章链接、同类题目归纳、通用解法总结等,还可以看到原题出现频率和相关企业等重要信息。如果有其他优选题解,还可以一同分享给他人。

由于本系列文章的内容随时可能发生更新变动,欢迎关注和收藏征服LeetCode系列文章目录一文以作备忘。

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 the board.
  • There must not be any empty cells ' ' or other lowercase letters directly left or right of 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.

题意:给你一个 m x n 的矩阵 board ,它代表一个填字游戏 当前 的状态。填字游戏格子中包含小写英文字母(已填入的单词),表示  格的 ’ ’ 和表示 障碍 格子的 ‘#’ 。

如果满足以下条件,那么我们可以 水平 (从左到右 或者 从右到左)或 竖直 (从上到下 或者 从下到上)填入一个单词:

  • 该单词不占据任何 '#' 对应的格子。
  • 每个字母对应的格子要么是 ' ' (空格)要么与 board 中已有字母 匹配 。
  • 如果单词是 水平 放置的,那么该单词左边和右边 相邻 格子不能为 ' ' 或小写英文字母。
  • 如果单词是 竖直 放置的,那么该单词上边和下边 相邻 格子不能为 ' ' 或小写英文字母。

给你一个字符串 word ,如果 word 可以被放入 board 中,请你返回 true ,否则请返回 false 。


解法1 枚举+剪枝+DFS

枚举所有可放置字符串首位的格子,注意判断各个边界条件(剪枝策略),比如相邻格子、是否越界等,然后DFS看看能否向上、下、左、右放置这个字符串:

//C++ version
class Solution {
private:
    int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    bool dfs(const vector<vector<char>>& b, const string& w, int i, int j, int k, int cur) {
        if (cur >= w.size()) return true;
        if (b[i][j] == '#' || (b[i][j] != ' ' && b[i][j] != w[cur])) return false;
        return dfs(b, w, i + d[k][0], j + d[k][1], k, cur + 1);
    }
public:
    bool placeWordInCrossword(vector<vector<char>>& board, string word) {
        int m = board.size(), n = board[0].size(), len = word.size();
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (board[i][j] != '#' && (board[i][j] == ' ' || board[i][j] == word[0])) {
                    int ti0 = i + len - 1, ti1 = i - len + 1, tj0 = j + len - 1, tj1 = j - len + 1; 
                    if ((ti0 < m && board[ti0][j] != '#') && //up to down
                        (i == 0 || board[i - 1][j] == '#') &&
                        (ti0 == m - 1 || board[ti0 + 1][j] == '#') &&
                        dfs(board, word, i, j, 0, 0)) return true;
                    if ((ti1 >= 0 && board[ti1][j] != '#') && //down to up
                        (i == m - 1 || board[i + 1][j] == '#') &&
                        (ti1 == 0 || board[ti1 - 1][j] == '#') &&
                        dfs(board, word, i, j, 1, 0)) return true;
                    if ((tj0 < n && board[i][tj0] != '#') && //left to right
                        (j == 0 || board[i][j - 1] == '#') &&
                        (tj0 == n - 1 || board[i][tj0 + 1] == '#') &&
                        dfs(board, word, i, j, 2, 0)) return true;
                    if ((tj1 >= 0 && board[i][tj1] != '#') && //right to left
                        (j == n - 1 || board[i][j + 1] == '#') &&
                        (tj1 == 0 || board[i][tj1 - 1] == '#') &&
                        dfs(board, word, i, j, 3, 0)) return true;
                }
            }
        }
        return false;
    }
};
//执行用时:148 ms, 在所有 C++ 提交中击败了99.73% 的用户
//内存消耗:58 MB, 在所有 C++ 提交中击败了51.91% 的用户

解法2 字符串匹配

题意很显然,字符串 word 只能放置在两个 # 之间的槽位(矩阵边界也视作 # ),于是可以遍历(正序+倒序)每个槽位,判断 word 能否恰好填入该槽位。虽然思路有些不同,但是核心想法与解法一也是一致的,相应代码就留待日后更新。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

memcpy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值