LetCode 79. 单词搜索

本文介绍了一种使用递归方法解决单词搜索问题的算法实现。该算法在二维字符网格中查找指定单词是否存在,通过深度优先搜索遍历网格,利用回溯策略验证单词的匹配情况。

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

// 递归求解
static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        if (word.length() <= 0)
            return false;
        if (board.size() <= 0 || board[0].size() <= 0)
            return false;
        vector<vector<bool>> visit(board.size(), vector<bool>(board[0].size(), false));
        for (int i = 0; i < board.size(); i++)
            for (int j = 0; j < board[0].size(); j++){
                if (word[0] == board[i][j])
                    if (solve(i, j, 0, board, word, visit))
                        return true;
            }
        return false;
    }
    
    bool solve(int row, int col, int index, vector<vector<char>>& board, string& word, vector<vector<bool>>& visit){
        if (index == word.length())
            return true;
        if (row >= board.size() || row < 0 || col >= board[0].size() || col < 0 || visit[row][col] ||word[index] != board[row][col])
            return false;
        
        visit[row][col] = true;
        // 四个方向尝试
        if (solve(row + 1, col, index + 1, board, word, visit) ||
            solve(row - 1, col, index + 1, board, word, visit) ||
            solve(row, col + 1, index + 1, board, word, visit) ||
            solve(row, col - 1, index + 1, board, word, visit))
            return true;
        // 记得还原标记
        visit[row][col] = false;         
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值