79. 单词搜索/C++

在这里插入图片描述

class Solution {
private:
    vector<vector<bool>> visit;
    int m,n;
    int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
    
    //判断点是否在范围内
    bool inarea(int x,int y){
        return x>=0 && y>=0 && x<m && y<n;
    }
    
    //index表示正在处理的位数
    bool search(vector<vector<char>>& board, string word, int index, int startx, int starty){
    	//如果在处理最后一位,那么直接判断最后一位是否相等即可
        if(index==(word.size()-1))
            return board[startx][starty] == word[index];
        
        //如果找到与word第index位相等的字符,则继续寻找下一个字符
        if(board[startx][starty] == word[index]){
            visit[startx][starty] = true;
            
            //上下左右寻找下一个
            for(int i=0;i<4;++i){
                int newx = startx + dir[i][0];
                int newy = starty + dir[i][1];
                
                if(inarea(newx,newy) && !visit[newx][newy]){
                    if(search(board,word,index+1,newx,newy)){
                        return true;
                    }
                }
            }
            //回溯
            visit[startx][starty] = false;
        }
        return false;
    }
public:
    bool exist(vector<vector<char>>& board, string word) {
        m=board.size();
        assert(m>0);
        n=board[0].size();
        
        for(int i=0;i<m;++i){
            visit.push_back(vector<bool>(n,false));
        }
        
        for(int i=0;i<m;++i){
            for(int j=0;j<n;++j){
                if(search(board,word,0,i,j)){
                    return true;
                }
            }
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/Zolewit/article/details/89554112
今日推荐