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.

For example,
Given board =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

这也算是设置标志位的经典例子了吧。(回溯)

class Solution {
public:
    bool isExist(vector<vector<char>>& board,string wordsub,int h,int w, vector<vector<bool>>&flag)
    {
        int direct[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
        for(int d=0;d<4;d++)
        {
            int jj=h+direct[d][0];
            int ii=w+direct[d][1];
            if(jj>=0&&jj<board.size()&&ii>=0&&ii<board[0].size())
            {
                if(wordsub[0]==board[jj][ii]&&flag[jj][ii]==0)
                {
                    flag[jj][ii]=1;
                    if(wordsub.size()==1||isExist(board,wordsub.substr(1),jj,ii,flag))
                        return true;
                    flag[jj][ii]=0;
                }
                
            }
                
        }
        return false;
    }
   
    bool exist(vector<vector<char>>& board, string word) {
        int length=word.size();
        int Height=board.size();
        int Width=board[0].size();
        vector<vector<bool>> flag(Height,vector<bool>(Width,0));
        for(int h=0;h<Height;h++)
            for(int w=0;w<Width;w++)
            {
                if(board[h][w]==word[0])
                {
                    flag[h][w]=1;
                    if( word.size()==1||isExist(board,word.substr(1),h,w,flag))
                        return true;
                    flag[h][w]=0;
                }
            }
        return false;
    }
};

 

转载于:https://www.cnblogs.com/qiaozhoulin/p/4528975.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值