Leetcode 79. Word Search

本文详细解析了LeetCode上单词搜索问题的解决方案,通过深度优先搜索算法在二维棋盘中查找目标单词,介绍了如何从每个可能的起点开始,递归地搜索剩余的字母,直到找到完整的单词。

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

https://leetcode.com/problems/word-search/description/

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.

solution
深搜,对目标字符串每一位,在棋盘中进行搜索

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size(), n = board[0].size();      // height and width
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(board[i][j] == word[0])      // 合法的起始点
                {
                    vector<vector<bool> > vis(m, vector<bool>(n, false));
                    vis[i][j] = true;
                    if(word.length() == 1)          // 只有一个字符的情况
                        return true;        
                    if(dfs(i, j, 1, board, word, vis) == true)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    // 现在处于棋盘的(x, y)位置,要搜索字符串的第 i 位
    bool dfs(int x, int y, int ind, vector<vector<char>> board, string word, vector<vector<bool> > vis)
    {
        int dx[4] = {1, 0, -1, 0};
        int dy[4] = {0, 1, 0, -1};
        int m = vis.size(), n = vis[0].size();
        for(int i=0;i<4;i++)
        {
            int newx = x+dx[i], newy = y+dy[i];
            if(newx>=m || newx<0 || newy>=n || newy<0 || vis[newx][newy] == true)
                continue;
            if(board[newx][newy] == word[ind])      // 这一位符合条件
            {
                if(ind == word.length()-1)      // 所有位都已经找到
                    return true;
                vis[newx][newy] = true;
                if(dfs(newx, newy, ind+1, board, word, vis) == true)        // 继续找下一位
                    return true;
                else
                {
                    vis[newx][newy] = false;
                    continue;
                }
            }
        }
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值