LeetCode 79. 单词搜索(C++) 回溯

给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

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

给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false

在这里插入图片描述

在这里插入图片描述
对表格中每个字母都进行回溯搜索,代码都有解释

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        rows = board.size(), columns = board[0].size();//获得行列的尺寸
        for(int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                if (backtrack(board, word, i, j, 0)) return true; // 每个格子都进行回溯判断
            }
        }
        return false;
    }

private:
    int rows, columns;
    bool backtrack(vector<vector<char>>& board, string& word, int x, int y, int index) {
        // 结束条件
        // 越界或者当前字母位不相等
        if (x >= rows || x < 0 || y >= columns || y < 0 || board[x][y] != word[index]) {
            return false;
        }
        // 最后一个字母也相等,返回成功
        if (index == word.size() - 1){
            return true;
        }
        // 避免重复使用
        board[x][y] = ' ';  //到达board[x][y] = ' ';的时候,表明已经满足条件board[x][y] == word[index]
        //因此,将board[x][y]旁边的点与 word[index+1]对比,所以避免重复使用将board[x][y]置空
        
        // 回溯
        if (backtrack(board, word, x - 1, y, index + 1)
        || backtrack(board, word, x + 1, y, index + 1)
        || backtrack(board, word, x, y - 1, index + 1) 
        || backtrack(board, word, x, y + 1, index + 1)) 
        {
            return true;
        }
        // 如果不通,回溯至上一个状态
        board[x][y] = word[index];
        return false;
    }
};

在这里插入图片描述

作者:wei-ming-26
链接:https://leetcode-cn.com/problems/word-search/solution/79-dan-ci-sou-suo-hui-su-dai-ma-jian-ji-y7rfq/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值