(102)79. 单词搜索

题目链接:
https://leetcode-cn.com/problems/word-search/
难度:中等
79. 单词搜索
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
	单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
	board =
	[
	  ['A','B','C','E'],
	  ['S','F','C','S'],
	  ['A','D','E','E']
	]
	给定 word = "ABCCED", 返回 true
	给定 word = "SEE", 返回 true
	给定 word = "ABCB", 返回 false
提示:
	board 和 word 中只包含大写和小写英文字母。
	1 <= board.length <= 200
	1 <= board[i].length <= 200
	1 <= word.length <= 10^3

我还以为题解有好方法的。。。 结果都一样 方法基本是一致的 就是枚举 一个个试。。。

class Solution {
    
    
public:
    vector<int> xdir={
    
    0,0,1,-1};
    vector<int> ydir={
    
    1,-1,0,0};

    bool exist(vector<vector<char>>& board, string word) {
    
    
        int n=board.size();
        int m=board[0].size();
        vector<vector<bool>> flag(n,vector<bool>(m));
        for(int i=0;i<n;++i){
    
    
            for(int j=0;j<m;++j){
    
    
                if(check(board,word,flag,i,j,0)){
    
    
                    return true;
                }
            }
        }
        return false;
    }

    bool check(vector<vector<char>>& board,string word,vector<vector<bool>>& flag,int i,int j,int k){
    
    
        if(board[i][j]!=word[k]){
    
    
            return false;
        }else if(k==word.length()-1){
    
    
            return true;
        }
        flag[i][j]=true;
        for(int t=0;t<4;++t){
    
    
            int x=xdir[t]+i;
            int y=ydir[t]+j;
            if(x>=0&&y>=0&&x<board.size()&&y<board[0].size()){
    
    
                if(!flag[x][y]){
    
    
                    if(check(board,word,flag,x,y,k+1)){
    
    
                        flag[i][j]=false;
                        return true;
                    }
                }
            }

        }   
        flag[i][j]=false;
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/li_qw_er/article/details/108568229