leetcode || 79、Word Search

本文介绍了一个二维网格中搜索特定单词的算法实现。采用深度优先搜索(DFS)策略,确保每个字母仅被使用一次,并详细展示了如何通过递归方法检查所有可能路径以找到目标单词。

problem:

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.

Hide Tags
  Array Backtracking
题意:在一个字符矩阵中搜索一个字,每个字符只能使用一次,搜索方向为上下左右

thinking:

(1)确定方法:全局搜索满足条件的解,使用DFS

(2)深搜成功的条件是:深搜成功一次,步数+1,直到深搜的步数达到word的长度

(3)新开一个矩阵大小的二维数组,记录矩阵的字符是否用过,先在矩阵中搜索word[0]的位置,一次为起点开始深搜,每次搜索上下左右四个方向

code:

class Solution {
private:
    bool flag;    
public:
    bool exist(vector<vector<char> > &board, string word) {
        int m=board.size();
        int n=board[0].size();
        int Maxdep=word.size();
        flag = false;
        vector<int> a1(n,0);
        vector<vector<int> > array(m,a1);
        for(int i=0;i<m;i++) //寻找搜索起点
        {
            for(int j=0;j<n;j++)
            {
                if(flag) //加快搜索
                    return true;
                if(board[i][j]==word[0])
                    dfs(0,Maxdep,i,j,array,board,word);
            }
        }
        return flag;
    }
protected:
    void dfs(int dep,int Maxdep,int x, int y,vector<vector<int> > &array,
                    vector<vector<char> > &board, string word)
    {
        if(flag)  //不能去掉,去掉就超时了
           return;
        int m=board.size();
        int n=board[0].size();
        if(dep==Maxdep) //这个必须放在x,y 边界判断的前面
        {
            flag=true;
            return ;
        }
        if(x<0 || x>=m || y<0 || y>=n)
            return;
        if(array[x][y]==1)
            return;
        if(board[x][y]==word[dep]) //四个方向深搜
        {
            array[x][y]=1;
            dfs(dep+1,Maxdep,x-1,y,array,board,word);
            dfs(dep+1,Maxdep,x,y-1,array,board,word);
            dfs(dep+1,Maxdep,x+1,y,array,board,word);
            dfs(dep+1,Maxdep,x,y+1,array,board,word);
            array[x][y]=0;
        }
        
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值