79. Word Search

本文介绍了一个算法问题,即在一个二维字符数组中查找指定单词的方法。通过递归方式检查每个单元格,判断是否能构成目标单词,并确保不重复使用同一单元格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]

Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
题目链接:


思路分析

给一个二维char数组和一个word,判断word能否由数组中连续的相邻的字母组成。

循环数组每一个位置的字母,递归判断由它开始,是否能够组成word。

递归开始,有若干结束条件,如果len == word.length()了,那么就是word中的字符都已经判断完成了,返回true;如果i或j越界了,返回false;如果board[i][j]不是对应word位置的字符,返回fasle。这些都满足的情况下,再对i,j位置周围的四个位置进行判断,递归调用existWord,返回调用的结果。

要注意的是,在进行BFS之前,要对已访问的节点进行标记,事后要再恢复,否则之后的搜索会出错。在代码中将它换成一个非字母的值就行。

代码
class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        for (int i = 0; i < board.size(); i++){
            for (int j = 0; j < board[0].size(); j++){
                if (existWord(board, i, j, word, 0))
                    return true;
            }
        }
        return false;
    }

    bool existWord(vector<vector<char>>& board, int i, int j, string word, int len){
        if (len == word.size()) return true;
        if (i < 0 || j < 0 || i == board.size() || j == board[0].size())
            return false;
        if (board[i][j] != word[len])
            return false;
        char temp = board[i][j];
        board[i][j] = '*';
        bool exist = existWord(board, i - 1, j, word, len+1) ||
                    existWord(board, i, j - 1, word, len+1) ||
                    existWord(board, i + 1, j, word, len+1) ||
                    existWord(board, i, j + 1, word, len+1);
        board[i][j] = temp;
        return exist;
    }
};

时间复杂度: O(mn)
空间复杂度: O(mn)


反思

又有点像我的人工智能项目了。如果知道可以重置恢复这一手,我就不用那么麻烦弄两个数组了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值