【leetcode】79. Word Search

本文详细阐述了使用深度优先搜索(DFS)算法解决单词搜索问题的方法,包括算法实现、核心逻辑以及应用实例。

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

简单的dfs

/**
 *  @author         johnsondu
 *  @time           20:01 8th Oct 2015
 *  @type           dfs
 *  @url            https://leetcode.com/problems/word-search/
 *  @status         Accepted
 */

class Solution {
public:
    void dfs(int x, int y, int idx, int len, int row, int col, vector<vector<bool>> &mark, bool &flag, vector<vector<char>>& board, string word)
    {
        if(flag) return;
        if(word[idx] != board[x][y]) return;
        if(idx == len - 1) {
            flag = true;
            return;
        }
        
        int dir[][2] = {1, 0, -1, 0, 0, 1, 0, -1};
        for(int k = 0; k < 4; k ++) {
            int tx = x + dir[k][0];
            int ty = y + dir[k][1];
            if(tx >= row || ty >= col || tx < 0 || ty < 0) continue;
            if(mark[tx][ty]) continue;
            mark[tx][ty] = true;
            dfs(tx, ty, idx + 1, len, row, col, mark, flag, board, word);
            mark[tx][ty] = false;
        }
    
    }
    
    bool exist(vector<vector<char>>& board, string word) {
        if(board.size() == 0) return false;
        if(word.size() == 0) return true;
        int row = board.size();
        int col = board[0].size();
        vector<vector<bool>> mark(board.size(), vector<bool>(board[0].size(), false));
        bool flag = false;
        int len = word.size();
        for(int i = 0; i < row; i ++) {
            for(int j = 0; j < col; j ++) {
                if(board[i][j] == word[0]) {
                    mark[i][j] = true;
                    dfs(i, j, 0, len, row, col, mark, flag, board, word);
                    mark[i][j] = false;
                    if(flag) return flag;
                }
            }
        }
        return flag;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值