【Leetcode】79. Word Search(DFS)

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.

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.

题目大意:

给出一个二维的数组,找出其中相邻元素(上下左右)是否能组成给出的一个Word,是的话返回true。

解题思路:

直接dfs,只faster than 5%。以后少写暴力搜索,当年写个搜索还行,现在懂行的人多了。搜索都变暴力。。。。:=(

class Solution {
private:
    bool ans;
    int xx[4] = {0,0,-1,1};
    int yy[4] = {-1,1,0,0};
    int n,m;
    int tmp;
    vector<vector<bool> > map_is; 
    void dfs(int x, int y,vector<vector<char> > board, string word){
        // cout<< x << " " << y << endl;
        // cout<< word.length() << endl;
        if(tmp==word.length()){
            ans = true;
            return;
        }
        for(int i=0;i<4;i++){
            int cor_x = x+xx[i];
            int cor_y = y+yy[i];
            if(vaild(cor_x,cor_y,board,word)){
                tmp++;
                map_is[cor_x][cor_y] = true;
                dfs(cor_x,cor_y,board,word);
                map_is[cor_x][cor_y] = false;
                if(ans == true) return;
                tmp--;
            }
        }
    }
    bool vaild(int x,int y,vector<vector<char> > board, string w){
        if(x < n&&x>=0&&y<m&&y>=0 ){
            if(board[x][y]==w[tmp]&&map_is[x][y]==false){
                return true;
            }
        }
        return false;
    }
public:
    bool exist(vector<vector<char>>& board, string word) {
        ans = false;
        n = board.size();
        m = board[0].size();
        for(int i = 0;i<n;i++){
            vector<bool> tmp_map;
            for(int j = 0;j<m;j++){
                tmp_map.push_back(false);
            }
            map_is.push_back(tmp_map);
        }
        
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                if(board[i][j]==word[0]){
                    tmp=1;
                    map_is[i][j] = true;
                    dfs(i,j,board, word);
                    map_is[i][j] = false;
                    if(ans == true) return ans;
                }
            }
        }

        
        return false;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值